我希望执行以下操作:
结构定义:
struct mystruct {
char cArr[500];
}
全局:
struct mystruct **ptr;
int count = 0;
在主要部分:
ptr = malloc(20*sizeof(struct test *));
for (int i = 0; i != 20 ; i++) {
ptr[i] = malloc(sizeof(struct test));
}
在某个被调用 20 次的函数中:
char burp[500];
//put whatever I want in burp;
ptr[count]->cArr = burp //is this right? Or do I have to memcpy to it, and if so how?
count++;
所以最后我将用我想要的字符依次填充 mystruct 数组。我尝试用 char** 执行此操作,但没有成功;我现在将它包装在一个结构中,因为它可以帮助我可视化正在发生的事情。
所以我想要一个 char[500] 的全局数组,每次调用函数时都会将该 char[500] 放入索引中(要么传递到函数中,要么传递到全局)。
如有任何建议,我们将不胜感激; Ofc 我还需要在最后释放数组的每个索引。
谢谢!
编辑:
所以会这样:
memcpy(ptr[count]->cArr, burp, 500);
然后工作吗?
最佳答案
#include <stdio.h>
#include <stdlib.h>
struct mystruct
{
char *cArr;
// U were trying to assign array using = operator
// Remember its not like in STL where u can perform deep copy of a vector
};
struct mystruct **ptr;
int count = 0;
int main()
{ int i;
ptr = malloc(20*sizeof(struct mystruct *));
for (i = 0; i != 20 ; i++)
{
ptr[i] = malloc(sizeof(struct mystruct));
}
char burp[500]="No this is not correct boy.";
//put whatever I want in burp;
(*ptr+count)->cArr = burp ;
// Assigning pointer to a pointer , OK. Remember pointer != Array.
//is this right? Or do I have to memcpy to it, and if so how?
//count++; // Has no use in your code, enclose in a loop to then use it.
printf("%s\n",(*ptr + count)->cArr); // This works , I think.
}
<小时/>
对于数组,即 char cArr[500],
如果你想使用 memcpy 你可以使用它:
memcpy((*ptr+count)->cArr, 打嗝, 500);
Strcpy 也可以工作:
strcpy((*ptr+count)->cArr, 打嗝);
有两点很重要:
允许将指针赋值给指针,但不允许对数组进行深拷贝。
**ptr 是一个双指针。因此,(*ptr + count ) 或 ptr[count] 是指向结构体的指针。
您的答案不需要第二点。
关于c - (C) 结构体数组并将数据移至其中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158883/