[英]Assigning string array to char**
I just cannot assign string array to my char** pointer. 我只是不能将字符串数组分配给我的char **指针。
I have my strings in char *tempArr[12];
我的字符串放在
char *tempArr[12];
But I don't know how to assign them to my char** arr variable. 但是我不知道如何将它们分配给我的char ** arr变量。
First, I allocate memory using: arr = (char**)malloc(numberOfElements * sizeof(char*));
首先,我使用以下方法分配内存:
arr = (char**)malloc(numberOfElements * sizeof(char*));
Then I tried to allocate memory to each element: 然后,我尝试为每个元素分配内存:
arr[i] = malloc(256 * sizeof(char));
I also tried to alocate just the memory for char pointer but neither works. 我也尝试只为char指针分配内存,但是都没有用。 The result in my arr variable is 2 to 3 nonsense characters.
我的arr变量的结果是2到3个废话字符。
What could be wrong? 有什么事吗 I tried everything I was able to find and the result is either crash or nonsense content.
我尝试了所有我能找到的东西,结果是崩溃或废话内容。
EDIT: Sorry I'll try to clarify it more. 编辑:对不起,我会尽力澄清一下。 Background is, I am loading data from file into structs.
背景是,我正在将数据从文件加载到结构中。 Each struct has
char**
variable that is suppose to hold strings array. 每个结构都有
char**
变量,该变量应该保存字符串数组。
In my reading code, I am using my temp array char* tempArr[12]
and successfully loading strings into it. 在我的阅读代码中,我正在使用临时数组
char* tempArr[12]
并将字符串成功加载到其中。 Then I pass it allong to my function that is creating my structs. 然后,将其传递给创建结构的函数。
The problem starts here, I was trying to "convert" my passed array so it can be stored in char** arr
variable. 问题从这里开始,我试图“转换”我传递的数组,以便可以将其存储在
char** arr
变量中。
char *tempArr[12];
Is array of pointers. 是指针数组。 So if you have something like
所以如果你有类似的东西
tempArr[0] = malloc(20);
strcpy(tempArr[0],"hello");
Then after what you are doing you can do. 然后在您做完之后就可以做。 ie After allocating memory to your the pointer
arr[i]
即在为您的指针
arr[i]
分配内存之后
char **arr = malloc(numberOfElements * sizeof(char*));
arr[i] = malloc(256);
strcpy(arr[i],tempArr[0]);
You can run the above steps in a loop to copy values for all your pointers 您可以循环执行上述步骤,以复制所有指针的值
I think that you mean the following 我认为你的意思是
#include <string.h>
//...
size_t i;
char **arr = ( char** )malloc( numberOfElements * sizeof( char* ) );
for ( i = 0; i < numberOfElements; i++ ) arr[i] = malloc( 256 * sizeof( char ) );
for ( i = 0; i < sizeof( tempArr ) / sizeof( *tempArr ); i++ ) strcpy( arr[i], tempArr[i] );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.