1

I want to store strings in a 2D array using pointers but I'm confused with how to do it. The examples I've seen use only arrays of ints or use the brackets[] to allocate a fixed size of memory. So I'm trying to initialize my 2D array of strings and this is what I have:

char ** stringArr = (char**)malloc(/*I don't know what goes here*/);
for(i = 0; i < rows; i++)
    stringArr[i] = (char*)malloc(cols *sizeof(char));

As you can see the parameter for my first call of malloc, I am stuck as to what to put there if I want an exact x number of rows, where each row stores a string of chars. Any help would be appreciated!

3 Answers 3

2

Do this, because you're allocating some number of pointers:

malloc(rows * sizeof(char*))
Sign up to request clarification or add additional context in comments.

Comments

0

You will want to use the number of rows.

char ** stringArr = malloc(rows * sizeof(char*));

Also, do not typecast the return value of a malloc() call.

2 Comments

Thanks for your reply but why shouldn't I typecast malloc()? Even cplusplus.com typecasts it in its reference page on malloc().
@Ghost_Stark Here is a protected link on the subject! Hope it makes things clearer : stackoverflow.com/questions/605845/…
0

Use sizeof *ptr * N.

Notice how this method uses the correct type even if stringArr was char ** stringArr or int ** stringArr.

stringArr = malloc(sizeof *stringArr * rows);
for(i = 0; i < rows; i++)
    stringArr[i] = malloc(sizeof *(stringArr[i]) * cols);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.