c - 将指针数组传递给结构体

标签 c

我正在制作一个简单的程序,将五个团队从第一名到第五名进行排序..但我想通过使用指针数组和传递结构方法来实现它。这就是我所做的..

#include <stdio.h>
#include <string.h>


struct league 
{
 char team1[20]; 
 char team2[20]; 
 char team3[20];
 char team4[20];
 char team5[20];
};


char *Arrange(struct league *table)

{
 struct league *Ptable[5] = {0};
  int i;

  Ptable[0]-> team5;
  Ptable[1]-> team2;
  Ptable[2]-> team3;
  Ptable[3]-> team1;
  Ptable[4]-> team4;

 for (i = 0; i < 5; i++)

  printf("%s\n", &Ptable[i]);

return Ptable[i];
}


int main()

{
struct league table;

 strcpy(table.team1,"Arsenal");
 strcpy(table.team2,"Man City");
 strcpy(table.team3,"LiverPool");
 strcpy(table.team4,"Totenham");
 strcpy(table.team5,"Chelsea");

printf("League table:\n");

 Arrange(&table);


return 0;
}  

当我编译它时,我收到此错误:

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘struct league **’ [-Wformat=]
   printf("%s\n", &Ptable[i]);

在不对我的代码进行太多更改的情况下编写此代码的正确方法是什么?因为我想在这样的代码中使用带有结构的指针数组。

最佳答案

联盟中的每支球队都是一个字符串,而不是一个结构体,因此您不需要一个结构体指针数组,只需要一个指向字符串的指针数组。

char *Arrange(struct league *table) {
    char *Ptable = malloc(5 * sizeof(char *));
    Ptable[0] = table->team5;
    Ptable[1] = table->team2;
    Ptable[2] = table->team3;
    Ptable[3] = table->team1;
    Ptable[4] = table->team4;
    for (i = 0; i < 5; i++) {
        printf("%s\n", &Ptable[i]);
    }
    return Ptable;
}

要返回一个数组,您需要使用 malloc() 动态分配它,然后返回该指针。

关于c - 将指针数组传递给结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42685144/

相关文章:

c - c中的奇怪行为

c - 共享库中的 gdb 断点不起作用

c++ - 一次性项目的脚手架/构建系统

c - Linux 中 C 的 sound() 和 nosound() 函数?

python - 按时钟并行输出视频

c++ - C 中的泛型指针和 C++ 中的泛型指针有哪些区别?

c++ - 有没有一个gcc命令可以链接同一目录下的所有.o文件并生成一个.exe文件?

C 预处理器 + 和 = 用法

sql - Oracle OCI 错误 : Segmentation fault (core dumped) when fetching 100000 rows

c - 获取带有日期和时间(包括微秒)的时间戳