为什么C程序中的segmentaion故障?

时间:2016-09-14 14:29:49

标签: c struct segmentation-fault

#include<stdio.h>
#include<stdlib.h>

struct keyVal
{
    int key;
    int val;
};

int main()
{

    struct keyVal *arr[5];
    int i;
    for(i=0;i<5;i++)
        printf("\n : %p     %p      ",&arr[i][0].val,&arr[i]);
    printf("\n\n");
    printf("\n : %d     %d      ",arr[0][0].val,arr[0]->val);
    printf("\n\n");

    for(i=0;i<5;i++)
        printf("\n : %d     %d      ",arr[i][0].val,arr[i]->val);
    printf("\n\n");

    return 0;
}

首先,for( ; ; );将从%p %parr[0][0]arr[4][0]arr[0]生成相同的arr[4],这意味着arr[i][0] == arr[i]其中i = 0,1,2,3,4

第二个for( ; ; );应打印arr[i][0].keyarr[i]->key)的值(垃圾值)。

我们可以通过以下方式访问密钥:

arr[i][0].keyarr[i]->key其中i = 0,1,2,3,4

3 个答案:

答案 0 :(得分:0)

你拿了5个指向keyVal结构的指针变量,没有分配内存,这就是它遇到分段错误的原因。使用malloc分配内存然后使用。

答案 1 :(得分:0)

您可以使用&amp; arr [i] .val而不是&amp; arr [i] [0] .val。

答案 2 :(得分:0)

请参阅评论以获得解释 我故意离开了最后for {...}我希望你能自己纠正

#include<stdio.h> 
#include<stdlib.h>

struct keyVal {
    int key;
    int val;
};

int main()
{
    /*
      You are creating an array composed of 5 cells.
      Each cell is bound to contain an address of a variable
      of which should be a keyVal.
    */
    struct keyVal *arr[5];
    int i;

    /* 
     Use curly brackets to wrap the content of the loop
     even though you only have one instruction it helps for readability
     and prevents errors.
    */
    for(i = 0; i < 5; i++) {
        printf(": %p | %p\n", &arr[i][0].val, &arr[i]);
    }

    /*
     You are getting a segmentation fault here because you are trying to access something which does not exist.
    */
    //printf(": %d - %d\n", arr[0][0].val, arr[0]->val);

    /***************************************************
     BEGIN CORRECTION :the field val will be initialized.
    ***************************************************/

    arr[0] = malloc(sizeof(struct keyVal)); // Allocating "sizeof(struct keyVal)" bytes in memory.
    arr[0]->val = 42; // Assigning a value to the field val in the first cell of arr. 
    printf(": %d | %d\n", arr[0][0].val, arr[0]->val); // Now we can print as a value now exists.

    /***************************************************
     END CORRECTION
    ***************************************************/
    /*
     Again use brackets ;p
     I think you can solve that one on your own, now.
    */  
    for(i = 0; i < 5; i++) {
        printf(": %d | %d \n", arr[i][0].val, arr[i]->val);
    }
    // Don't forget to free "ALL" the memory allocated with malloc.
    free(arr[0]);

    return 0;
}

了解malloc and free