如何初始化C字符串的二维数组的行 [英] 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));
正如你所看到的参数为我的malloc第一个电话,我坚持以什么放在那里,如果我想准确的行x个,每行的字符存储的字符串。任何帮助将是AP preciated!
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!
推荐答案
这样做,因为你的指针分配一定数量的:
Do this, because you're allocating some number of pointers:
malloc(rows * sizeof(char*))
这篇关于如何初始化C字符串的二维数组的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!