Segmentation Fault - declare and init array in C

后端 未结 3 1569
渐次进展
渐次进展 2021-01-28 10:12

I am very new to C. coming from Python, Java and C# worlds. This might be a stupid question but I am getting segmentation fault:

// struct for storing matrices
t         


        
3条回答
  •  没有蜡笔的小新
    2021-01-28 10:16

    In C arrays and pointers are related, but they are not the same. It is not enough to declare a pointer in order to make it an array: you need to set that pointer to a value pointing to a block of memory of sufficient size.

    To make your example work, add

    A.elts = malloc(sizeof(float) * 9);
    

    before calling memcpy. Otherwise, the pointer elts remains uninitialized, so writing to memory pointed by that pointer is undefined behavior. Note that you would need to call free(A.elts) when you are done with the array.

    Another alternative would be declaring elts as a fixed-size array, not as a pointer:

    float elts[9];
    

    This would not allow resizing the array, though.

提交回复
热议问题