开发者

Accessing Structure elements in C

I am trying to access the element asd7 inside the innermost structu开发者_运维技巧re, here is my code:

#include <stdio.h>

int main()
{
 struct asd
 {
  int asd;
  struct asd1
  {
   int asd1;
   struct asd6
   {
    int asd7;
   }asd6;
  }asd1;
 }asd;
 int asd10;
 int asd11;
 struct asd *ptr1;
 struct asd1 *ptr2;
 struct asd6 *ptr3;
 asd.asd1.asd6.asd7=10; 
 printf("%d\n",asd.asd1.asd6.asd7);

}

The code is compiling but I am unable to run it - I am getting a segmentation fault. Any help would be great.

Thanks

The output is:

10

Exited: ExitFailure 3


There's nothing wrong with your code that a simple return 0; at the end wouldn't fix :-)

Without:

pax> cat qq.c ; gcc -o qq qq.c ; ./qq ; echo rc=$?

#include <stdio.h>
int main (void) {
    struct asd {
        int asd;
        struct asd1 {
            int asd1;
            struct asd6 {
                int asd7;
            } asd6;
        } asd1;
    } asd;
    asd.asd1.asd6.asd7=10;
    printf("%d\n",asd.asd1.asd6.asd7);
    //return 0;
}

10
rc=3

With:

pax> cat qq.c ; gcc -o qq qq.c ; ./qq ; echo rc=$?

#include <stdio.h>
int main (void) {
    struct asd {
        int asd;
        struct asd1 {
            int asd1;
            struct asd6 {
                int asd7;
            } asd6;
        } asd1;
    } asd;
    asd.asd1.asd6.asd7=10;
    printf("%d\n",asd.asd1.asd6.asd7);
    return 0;
}

10
rc=0

The other alternative is to switch to a C99 compiler (or mode). The C99 standard states, in part (paraphrased):

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument: reaching the } that terminates the main function returns a value of 0.

(my italics).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜