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. char *test = "test".
When开发者_JAVA技巧 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.
aStruct->anArray[0]->string = test;
aStruct contains a char** anArray and char *string. char *test = "test".
Is that command not valid?
Certainly not. aStruct->anArray[0]
would be char*
and wouldn't have a member ->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. 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.
精彩评论