[英]Passing a structure pointer as a function argument (Seg fault unknown)
Header file #1 "city.h" 头文件#1“ city.h”
typedef struct City{
double* lat;
double* lon;
double* pop;
char* airport;
char* name;
}City;
Header file #2 "vector.h" 头文件#2“ vector.h”
typedef struct Vector{
City* cityArray[26]; // 26 pointers to struct City
}Vector;
C file C档
#include "vector.h"
#include "city.h"
#include <stdlib.h>
void init(Vector *ptr) {
ptr->cityArray[0]->name = "hi"; // Error Seg Fault!
}
Hi, Your suggestion did work, but for some reason I'm getting Seg faults now even though the I'm 100% sure the code didn't change. 嗨,您的建议确实奏效了,但是由于某种原因,即使我100%确信代码没有更改,我现在也遇到了Seg错误。 Could you see whats wrong?
你能看出什么问题吗?
Try this - 尝试这个 -
ptr->cityArray[0]->name = "hi"; // ptr is pointer to struct vector
As cityArray
is a member variable of struct Vector
, access it using a struct variable or pointer . 由于
cityArray
是struct Vector
的成员变量,因此请使用struct变量或指针对其进行访问。
Can't do this cityArray[0]->name = "hi";
无法执行此
cityArray[0]->name = "hi";
because cityArray
is not any independent array of pointers. 因为
cityArray
不是任何独立的指针数组。
As you get segmentation fault , you need to allocate memory to struct pointer ptr
as well as to char *
present in struct city
. 当您遇到分段错误时,需要将内存分配给结构指针
ptr
以及结构city
char *
。
In function do it like this - 在功能上做到这一点-
ptr=malloc(sizeof(Vector));
ptr->cityArray[0]->name=malloc(3); // size 3 to store "hi" you can give desired size.
But remember to free
allocated memory. 但是请记住
free
分配的内存。
In your case, vector.h appears before city.h . 就您而言, vector.h出现在city.h之前。 You need to put city.h before vector.h to make the definition of
city
visible to vector
. 你需要把city.h vector.h之前做出的定义
city
可见的vector
。
That said, cityArray
itself is not an independent variable , it is called a member variable. 也就是说,
cityArray
本身不是自变量 ,因此称为成员变量。 You need to have a variable of the structure type to make use of cityArray
. 您需要具有结构类型的变量才能使用
cityArray
。 Something like 就像是
Vector Vec;
Vec.cityArray[0]->name ....
and so on. 等等。 Also make a note about the type of the variable and the initializer used.
还要记下变量的类型和使用的初始化程序。 They both should match.
他们都应该匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.