简体   繁体   中英

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!

这样做是因为您要分配一些指针:

malloc(rows * sizeof(char*))

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM