I'm trying to run the following code(in gcc 4.3 on fedora 11 i586 ):
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
struct s_smallstruct{
int smallstruct;
};
struct s_test2{
char * test2;
struct s_smallstruct* smallstruct;
};
struct s_test3{
char * test3;
struct s_smallstruct * smallstruct;
};
struct s_test1{
char * test1;
struct s_test2 * test2;
struct s_test3 * test3;
};
int main(){
struct s_test1 *test1 = (struct s_test1 *) malloc( sizeof test1 );
test1->test2[0].smallstruct[0].smallstruct = 123;
int num = test1->test2[0].smallstruct[0].smallstruct;
// struct s_smallstruct * smallstruct = (struct s_smallstruct *) malloc( sizeof smallstruct );
// smallstruct[0].smallstruct =12;
// int num = smallstruct[0].smallstruct;
printf( "%d\n" , num );
return EXIT_SUCCESS;
}
But I got a segfault at test1->test2[0].smallstruct[0].smallstruct = 123; . Commented part is running without error. What is the reason of this behaviour. I'm not very proficient in C , so I'd appreciate any kind of help.
There are three problems with your code that I can see:
Here is something that works:
const int length = 2;
struct s_test1 *test1 = malloc( length * sizeof *test1 );
test1->test2 = malloc( length * sizeof *test1->test2 );
test1->test2->smallstruct = malloc( length * sizeof *test1->test2->smallstruct );
test1[1].test2[0].smallstruct[1].smallstruct = 123;
int num = test1[1].test2[0].smallstruct[1].smallstruct;
Try changing:
struct s_test1 *test1 = (struct s_test1 *) malloc( sizeof test1 );
to
struct s_test1 *test1 = (struct s_test1 *) malloc( sizeof struct s_test1 );
test1 is a pointer, which in 32bit environments is 4 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With