David Velasquez
David Velasquez

Reputation: 2366

How to initialize rows of 2D array of strings in C

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!

Upvotes: 1

Views: 109

Answers (3)

chux
chux

Reputation: 153507

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);

Upvotes: 0

Corb3nik
Corb3nik

Reputation: 1177

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.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249213

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

malloc(rows * sizeof(char*))

Upvotes: 2

Related Questions