c - Pointer to struct within the nested structs -


I am trying to run the following code (in GCC 4.3 on fedora 11 i586):

  #include & lt; Stdio.h & gt; # Include & lt; Stdint.h & gt; # Include & lt; Stdlib.h & gt; Straight 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 (size testof 1); Test1- & gt; Test 2 [0] .smallstruct [0] .smallstruct = 123; Intuit = Test 1- & gt; Test 2 [0]. Smlstruct [0] .smallstruct; // straight s_smallstruct * smallstruct = (straight s_smallstruct *) malloc (size smallstruct); // small edit [0] .smallstruct = 12; // integer number = small structure [0] .smallstruct; Printf ("% d \ n", number); Return EXIT_SUCCESS; }  

But I've got a sygfault on test1-> test2 [0]. [0]. Smaltstruct [0] .smallstruct = 123; . Part of the comment is running without error, what is the reason for this behavior? I am not very skilled at C, so I appreciate any kind of help.

Three problems with your code that I can get:

  1. sizeof only tells you the size of the pointer, which is 4 for 32-bit pointers, the structure of the shape is not indicated,
  2. and even If you specify the size of the structure to change the size of the shape, malloc will only assign memory to s_test1 structure, not for structures, which indicate from within it Is performed ,
  3. And finally, there should be pointers in test1 , test2 etc. Initialized.

Here's something that:

  const int length = 2; Struct s_test1 * test1 = malloc (length * size * test1); Test1- & gt; Test2 = malloc (length * size * test1-> test2); Test1- & gt; Test2- & gt; Smallstruct = malloc (length * size * test1-> test2- & gt; smallstruct); Test1 [1] .test2 [0] .smallstruct [1] .smallstruct = 123; Int num = test1 [1] .test2 [0] .smallstruct [1] .smallstruct;  

Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -