簡體   English   中英

向量分割錯誤結構體的指針

[英]Pointer of a struct with vector - Segmentation Fault

為什么我不能給qtd_lines

typedef struct{
  int x;
  int y;
  char z;
}struct_c;

typedef struct{
   int qtd_lines;
   struct_c *vector;
}struct_a;

int main(){
 struct_a *pointer;

//This gives me Segmentation Fault.
 pointer->qtd_lines = 10;
 pointer->vetor = (struct_c *)  malloc(pointer->qtd_lines * sizeof(struct_contas));

 return 0;
}

好的,我的struct_c有一個向量,但是qtd_lines字段不是向量,對嗎? 那么,為什么會出現此錯誤?

指針存儲內存地址。

struct_a *pointer;

這只是聲明一個包含一些內存地址的變量。 在該內存地址處可能有一個struct_a對象,也可能沒有

那么如何知道pointer是否pointer實際對象呢? 您必須為指針分配一個內存地址。


您可以動態分配一個內存塊來保存該對象,然后將該內存的地址分配給pointer

pointer = malloc(sizeof(struct_a));

或者,您可以在堆棧上分配對象,然后將該對象的內存地址存儲在指針中:

struct_a foo;
pointer = &foo;

但是就目前而言,代碼pointer沒有指向任何內容,而是使用->運算符訪問指針指向的內存。

在C語言中,您實際上可以做到這一點,但是卻得到了不確定的行為。 像是分割錯誤。 或者可能只是怪異的行為。 一切皆有可能。

因此,在使用它之前,只需使指針指向某個東西即可。

pointer->qtd_lines = 10; 正在未分配的位置寫入。 您需要初始化pointer

 struct_a *pointer = malloc(struct_a);

在您的情況下,僅聲明結構指針。 沒有為此分配內存。

這樣分配:

struct_a* pointer = (struct_a*)malloc(sizeof(struct_a));

同樣,一旦完成您的工作,請不要忘記釋放該內存,因為它是從堆內存段中獲取的。

free(pointer);

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM