[尝试初始化一个函数,以便其数据成员的数值为0,字符串为“ none”,但strcpy发生分段错误。
这是用于创建由x,y点组成的2d数组的代码,在以后的功能之前,我需要将函数初始化为默认值(0和无)。我试图弄乱指针,而不是使用strcpy,但据我了解,更新字符串需要strcpy。
typedef struct Hill {
char name[20];
int loc[2];
double height;
double slope;
} Hill;
Hill* setHill (Hill* hill){
strcpy(hill->name, "none"); // error appears to be here
hill->loc[0] = 0;
hill->loc[1] = 0;
hill->height = 0;
hill->slope = 0;
return hill;
}
int main() {
Hill* hillsArray[5];
int i;
// calling setHill to populate an array of 5 hills
for(i=0; i<5; ++i) {
setHill(hillsArray[i]);
}
// updating hill "ada's apex"
strcpy((hillsArray[0]->name), "Ada's Apex");
hillsArray[0]->loc[0] = 12;
hillsArray[0]->loc[1] = 9;
hillsArray[0]->height = 20;
hillsArray[0]->slope = 0.25;
// updating hill turing's top
strcpy((hillsArray[1]->name), "Turing's top");
hillsArray[1]->loc[0] = 4;
hillsArray[1]->loc[1] = 3;
hillsArray[1]->height = 20;
hillsArray[1]->slope = 0.33;
此山的更新对总共5个山重复了3次以上,但其相同的代码只是用不同的值更新了每个山。
至少有一个问题,您没有为希尔斯分配任何内存。 Hill* hillsArray[5];
是Hill
pointers的数组。它们指向无处,因此,当您执行hill->name
时,您将取消引用错误的指针,这是未定义的行为,在您的情况下,该错误将自身表现为段错误。您需要为每个Hill
对象动态或自动分配内存,如下所示:
// dynamically (following what you have now)
int main() {
Hill* hillsArray[5];
int i;
// calling setHill to populate an array of 5 hills
for(i=0; i<5; ++i) {
hillsArray[i] = malloc(sizeof(hillsArray[0])); // equivalent to malloc(sizeof(struct Hill));
if (hillsArray[i] == NULL)
{
// in the case the malloc fails, handle the error however you want
printf("Could not allocate memory for Hill %d\n", i);
return 1;
}
setHill(hillsArray[i]);
}
....
// it's considered good practice to clean up memory you dynamically allocate,
// although you will find differing opinions on that on SO, so up to you
for (i=0; i<5; i++)
{
free(hillsArray[i]);
}
或者如果您不想弄乱动态分配内存(除非我have来做,否则,您可以]
// setup Hills in automatic storage instead
int main() {
Hill hillsArray[5]; // each hill is in automatic storage, probably on the stack
int i;
// calling setHill to populate an array of 5 hills
for(i=0; i<5; ++i) {
setHill(&(hillsArray[i])); // now you must pass the address of each Hill to the setHill function
}
....
// since it's automatic storage, no need to clean it up yourself
}