Segmentation Fault when attempting to print value in C

后端 未结 3 1379
夕颜
夕颜 2020-12-07 01:47

The following C code returns a \"segmentation fault\" error. I do not understand why it does not return the value 20. What is my error?

#include 

        
3条回答
  •  失恋的感觉
    2020-12-07 02:37

    You are trying to write 20 in garbage value. You must allocate space for it by using one of *alloc() functions or creating an int on stack and getting the andress of it(as Richard J. Ross III mentioned on comments).

    dynamic allocation:

    int n*; 
    n = malloc(sizeof(int));  /* allocate space for an int */
    if(n != NULL) {
     /* do something.. */ 
     free(n); /* free 'n' */
    } else {
      /*No space available. */
    }
    

    or on the stack:

    int int_on_stack;
    int *n = &int_on_stack;
    *n = 20;
    printf("%i\n", *n); // 20
    

提交回复
热议问题