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!

David Velasquez
  • 2,346
  • 1
  • 26
  • 46

3 Answers3

2

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

malloc(rows * sizeof(char*))
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
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.

Corb3nik
  • 1,177
  • 7
  • 26
  • Thanks for your reply but why shouldn't I typecast malloc()? Even cplusplus.com typecasts it in its reference page on malloc(). – David Velasquez Sep 29 '15 at 02:35
  • @Ghost_Stark Here is a protected link on the subject! Hope it makes things clearer : http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Corb3nik Sep 29 '15 at 02:36
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);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256