简体   繁体   English

将Struct数组作为指针传递

[英]Passing A Struct array as a pointer

I would like to pass the struct array as an argument of the print function and then acces its members for printing. 我想将struct数组作为打印函数的参数传递,然后访问其成员进行打印。 Why do I get a pointer error when I dont apss any pointers? 当我不分配任何指针时,为什么会出现指针错误?

in main.c: 在main.c中:

struct city {
    double longitude;
    double latitute;
    char name[buf_size]; 
};
int numCitToRead = 10;
struct city cities[25];
printCities(&numCitToRead, cities);

Note: The Struct array gets initialised in a file parsing function. 注意:Struct数组在文件解析功能中初始化。 It is always 25 fields long, but if numCitToRead is 10, Only 10 fields will be filled 它始终为25个字段,但如果numCitToRead为10,则仅填充10个字段

int printCities(int* t_numCitToRead, struct city t_cities[25]) {

    for (unsigned short i = 0; i < *t_numCitToRead; i++) {
        printf("\n\n\tCity %d: ", i+1);
        printf("\nname:\t\t%s", t_cities[i].name);
        printf("\nlongitude:\t%f", t_cities[i].longitude);
        printf("\nlatitude:\t%f", t_cities[i].latitute);
    }
    return 0;
}

I hope someone can help me! 我希望有一个人可以帮助我!

Greetings 问候

Have modified the code and its working now. 现在已经修改了代码及其工作。 let's try it: 让我们尝试一下:

#include <stdio.h>

struct city {
    double longitude;
    double latitute;
    char *name; 
  };

int printCities(int* t_numCitToRead, struct city t_cities[25]) {

    for (unsigned short i = 0; i < *t_numCitToRead; i++) {
    printf("\n\n\tCity %d: ", i+1);
        printf("\nname:\t\t%s", t_cities[i].name);
        printf("\nlongitude:\t%f", t_cities[i].longitude);
        printf("\nlatitude:\t%f", t_cities[i].latitute);
    }
    return 0;
}

int main() {
  int numCitToRead = 10;
  struct city cities[25];
  // create dummy data
  for(int i =1; i<=25; i++)
  {
   cities[i-1].name = "name";
   cities[i-1].longitude =  10 * i;
   cities[i-1].latitute = 10 * 20;
  } 
 printCities(&numCitToRead, cities);
 return 0;
}

Thanks! 谢谢!

Thanks to everyone for the great support and helpful comments and suggestions. 感谢大家的大力支持和有用的评论和建议。

After adjusting a few different things which were pointed out by people in this thread, it finally compiled succesfully. 在调整了该线程中人们指出的一些不同的东西之后,它终于成功编译了。

The things I adjusted were: 我调整的是:

  • inlcuded the header file to the city struct data type definition in the printFunctions file 将头文件包含到printFunctions文件中的city struct数据类型定义中

  • initialized the struct to resolve pointer errors 初始化结构以解决指针错误

Thanks for the great feedback and comments / suggestions. 感谢您的宝贵意见和评论/建议。

Have a nice day! 祝你今天愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM