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

标签 c pointers structure

头文件#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/

相关文章:

c - for(i=0;i<10000000000;++i) 编译成无限循环?

我可以通过 char* 指针访问 int 变量的每个字节吗?

c++指向函数赋值的指针

C 写入文件的可重复选择问题

c - 在C中的字结构数组中存储元素

c - 如何在不进行类型转换的情况下通过乘法避免整数溢出?

c - 使用 ASM 内联汇编(64 位)进行冒泡排序的奇怪排序问题

c++ - 扫描字符串每个字符的ASCII值

c# - 我们能否在 C# 中重载 Point 对象以使其支持 double ?

c++ - 字符串和结构的代码块错误