[英]Pointer of a struct with vector - Segmentation Fault
Why can't I assign a value to qtd_lines
? 为什么我不能给
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;
}
Ok, I have a vector in my struct_c
, but the field qtd_lines
is not a vector, right ? 好的,我的
struct_c
有一个向量,但是qtd_lines
字段不是向量,对吗? So Why am I getting this error ? 那么,为什么会出现此错误?
Pointers store memory addresses only . 指针仅存储内存地址。
struct_a *pointer;
This just declares a variable that holds some memory address. 这只是声明一个包含一些内存地址的变量。 At that memory address there might be a
struct_a
object, or there might not be. 在该内存地址处可能有一个
struct_a
对象,也可能没有 。
Then how do you know whether pointer
points to an actual object or not? 那么如何知道
pointer
是否pointer
实际对象呢? You have to assign a memory address to the pointer. 您必须为指针分配一个内存地址。
You can either dynamically allocate a block of memory to hold the object, and assign the address of that memory to pointer
: 您可以动态分配一个内存块来保存该对象,然后将该内存的地址分配给
pointer
:
pointer = malloc(sizeof(struct_a));
Or you can allocate the object on the stack, and then store the memory address of that object in the pointer: 或者,您可以在堆栈上分配对象,然后将该对象的内存地址存储在指针中:
struct_a foo;
pointer = &foo;
But as it stands, in your code pointer
doesn't point to anything, but you use the ->
operator to access the memory that the pointer points to. 但是就目前而言,代码
pointer
没有指向任何内容,而是使用->
运算符访问指针指向的内存。
And in C you actually can do that, but you get undefined behavior. 在C语言中,您实际上可以做到这一点,但是却得到了不确定的行为。 Like a segmentation fault.
像是分割错误。 Or possibly just weird behavior.
或者可能只是怪异的行为。 Anything is possible.
一切皆有可能。
So, just make the pointer point to something before using it. 因此,在使用它之前,只需使指针指向某个东西即可。
pointer->qtd_lines = 10;
is writing at unallocated location. 正在未分配的位置写入。 You need to initialize
pointer
. 您需要初始化
pointer
。
struct_a *pointer = malloc(struct_a);
In your case only structure pointer is declared. 在您的情况下,仅声明结构指针。 No memory is allocated for that.
没有为此分配内存。
Assign this like so: 这样分配:
struct_a* pointer = (struct_a*)malloc(sizeof(struct_a));
Also once you done your things please don't forget to free that memory since it was taken from the Heap memory segment. 同样,一旦完成您的工作,请不要忘记释放该内存,因为它是从堆内存段中获取的。
free(pointer);
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.