[英]How do I insert a value for an element of an array that is pointed by a pointer in a struct
I currently have a struct that contains a pointer to an array of pointers. 我目前有一个结构,其中包含一个指向指针数组的指针。 I am trying to give a value to an element in the array of pointers, but I get a segmentation fault.
我试图给指针数组中的一个元素赋值,但是遇到了段错误。
aStruct->anArray[0]->string = test;
aStruct contains a char** anArray and char *string. aStruct包含一个char ** anArray和char * string。 char *test = "test".
char * test =“测试”。
When I try to do what I did, I get a segmentation fault. 当我尝试做我做的事情时,我遇到了分割错误。 Is that command not valid?
该命令无效吗?
struct aStruct
{
char **anArray;
};
I used calloc to make an array of size 10. 我用calloc制作了一个大小为10的数组。
aStruct->anArray[0]->string = test;
aStruct contains a char** anArray and char *string.
aStruct包含一个char ** anArray和char * string。 char *test = "test".
char * test =“测试”。
Is that command not valid?
该命令无效吗?
Certainly not. 当然不是。
aStruct->anArray[0]
would be char*
and wouldn't have a member ->string
. aStruct->anArray[0]
将为char*
并且没有成员->string
。
Other than that, if it really compiles and you only posted the wrong code, you wouldn't get a segmentation fault if anArray
was properly allocated and had the right size. 除此之外,如果它确实可以编译并且您只发布了错误的代码,则如果正确分配
anArray
并具有正确的大小,就不会出现分段错误。 So you need something like this in your program: 因此,您在程序中需要这样的内容:
aStruct->anArray = malloc(size * sizeof(*aStruct->anArray));
where size is at least one for your case, but generally the number of elements you ever need to access. 其中大小至少为一种,但通常需要访问的元素数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.