简体   繁体   English

如何为结构体中的指针所指向的数组元素插入值

[英]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.

相关问题 如何初始化指针指向的结构的成员? - How do I initialize members of a struct that is pointed to by a pointer? 您如何访问指针数组内部的指针所指向的值? - How do you access the value pointed to by a pointer inside of an array of pointers? 如何在指向其他结构的结构指针中打印值? - How to print a value in a struct pointer pointed for other struct? 如何使结构内的指针指向另一个指针指向的同一个字符串? - How do I make a pointer inside a struct point to the same string pointed by another pointer? C中的结构体中的指针指向的自由数组 - Free array pointed to by a pointer within a struct in C 如何获得用指针指向的二维数组的宽度/高度? - How do I get the width/height of a 2d array being pointed to with my pointer? 在指针数组中打印指针指向的值 - Printing value pointed by pointer within array of pointer 如何在C中的结构指针处为数组中的元素分配值 - How to assign value for element in array at struct pointer in C 如何将自定义结构插入另一个保存初始结构二维指针的结构? - How do I insert a custom struct into another struct that holds a 2 dimensional pointer of the initial struct? 如何从指向该数组的指针中提取“ struct *”数组(在JNA中)? - How do I extract an array of `struct*` from a pointer to that array (in JNA)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM