gpt4 book ai didi

c - 将结构指针作为函数参数传递(段错误未知)

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:56 25 4
gpt4 key购买 nike

头文件#1“city.h”

typedef struct City{

double* lat;
double* lon;
double* pop;


char* airport;
char* name;


}City;

头文件#2“vector.h”

typedef struct Vector{


City* cityArray[26]; // 26 pointers to struct City


}Vector;

C文件

#include "vector.h"
#include "city.h"
#include <stdlib.h>


void init(Vector *ptr) {

ptr->cityArray[0]->name = "hi"; // Error Seg Fault!

}

您好,您的建议确实有效,但出于某种原因,我现在遇到段错误,尽管我 100% 确定代码没有更改。你能看出哪里出了问题吗?

最佳答案

试试这个-

  ptr->cityArray[0]->name = "hi";       // ptr is pointer to struct vector

因为 cityArray 是结构 Vector 的成员变量,所以使用结构变量或指针访问它。

不能这样做cityArray[0]->name = "hi";因为 cityArray 不是任何独立的指针数组。

编辑

当您遇到段错误时,您需要为结构指针 ptr 以及结构 city 中的 char * 分配内存。

在函数中这样做 -

ptr=malloc(sizeof(Vector));
ptr->cityArray[0]->name=malloc(3); // size 3 to store "hi" you can give desired size.

但请记住释放分配的内存。

关于c - 将结构指针作为函数参数传递(段错误未知),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com