带向量的结构指针 - 分段错误
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
不是矢量,对吗?那么为什么我会收到此错误?
pointer->qtd_lines = 10;
正在未分配的位置写入。您需要初始化 pointer
。
struct_a *pointer = malloc(struct_a);
指针存储内存地址仅.
struct_a *pointer;
这只是声明了一个包含一些内存地址的变量。在那个内存地址,可能是一个struct_a
对象,或者可能不是。
那你怎么知道pointer
是否指向一个实际的对象呢?您必须为指针分配一个内存地址。
您可以动态分配一块内存来保存对象,并将该内存的地址分配给 pointer
:
pointer = malloc(sizeof(struct_a));
或者你可以在栈上分配对象,然后在指针中存储那个对象的内存地址:
struct_a foo;
pointer = &foo;
但就目前而言,在你的代码中 pointer
没有指向任何东西,但你使用 ->
运算符访问指针指向的内存。
而在 C 中你实际上 可以 这样做,但是你会得到未定义的行为。就像分段错误。或者可能只是奇怪的行为。一切皆有可能。
所以,在使用之前让指针指向某物。
在你的例子中,只声明了结构指针。没有为此分配内存。
像这样分配:
struct_a* pointer = (struct_a*)malloc(sizeof(struct_a));
此外,一旦你完成了你的事情,请不要忘记释放该内存,因为它是从堆内存段中获取的。
free(pointer);
希望对您有所帮助。
为什么我不能给 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
不是矢量,对吗?那么为什么我会收到此错误?
pointer->qtd_lines = 10;
正在未分配的位置写入。您需要初始化 pointer
。
struct_a *pointer = malloc(struct_a);
指针存储内存地址仅.
struct_a *pointer;
这只是声明了一个包含一些内存地址的变量。在那个内存地址,可能是一个struct_a
对象,或者可能不是。
那你怎么知道pointer
是否指向一个实际的对象呢?您必须为指针分配一个内存地址。
您可以动态分配一块内存来保存对象,并将该内存的地址分配给 pointer
:
pointer = malloc(sizeof(struct_a));
或者你可以在栈上分配对象,然后在指针中存储那个对象的内存地址:
struct_a foo;
pointer = &foo;
但就目前而言,在你的代码中 pointer
没有指向任何东西,但你使用 ->
运算符访问指针指向的内存。
而在 C 中你实际上 可以 这样做,但是你会得到未定义的行为。就像分段错误。或者可能只是奇怪的行为。一切皆有可能。
所以,在使用之前让指针指向某物。
在你的例子中,只声明了结构指针。没有为此分配内存。
像这样分配:
struct_a* pointer = (struct_a*)malloc(sizeof(struct_a));
此外,一旦你完成了你的事情,请不要忘记释放该内存,因为它是从堆内存段中获取的。
free(pointer);
希望对您有所帮助。