You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中如何将结构体的二维数组传递给函数?

结构体二维数组传递与访问错误的修复

你的代码存在两个核心问题,直接导致了输出顺序错误和段错误:

1. 指针访问逻辑完全错误

原printA函数里的(*((arrayA+j) + i))->name是完全错误的索引方式:

  • arrayA是Person**类型,arrayA[i]指向的是每个子数组(比如array1或array2)的首地址
  • 正确的访问方式应该是arrayA[i][j].name,或者等价的(*(arrayA[i] + j)).name
  • 你原来的写法不仅搞反了i和j的顺序,还错误地进行指针偏移,当循环到i=1、j=1时,会访问到arrayMain数组之外的内存,直接触发段错误

2. 函数未返回值

printA声明返回int,但函数体内没有任何return语句,这属于未定义行为,可能引发额外的程序异常


修正后的完整代码:

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

typedef struct Person {
    char name[100];
    int age;
    char secondName[100];
} Person;

// 修正指针访问逻辑,同时添加返回值
int printA(Person **arrayA) {
    printf("here\n\n");
    int i;
    int j;
    for(i=0; i<2; i++) {
        for(j=0; j<3; j++) {
            // 正确的访问方式:先取第i个子数组,再取第j个元素
            printf("%s\n", arrayA[i][j].name);
            // 也可以写成 (*(arrayA[i] + j)).name,效果完全一致
        }
        printf("DONE Array\n\n");
    }
    // 添加返回值,符合函数声明
    return 0;
}
 
int main()
{
    Person person1;
    Person person2;
    Person person3;
    Person person4;
    Person person5;
    Person person6;
    
    strcpy(person1.name, "John");
    strcpy(person2.name, "Will");
    strcpy(person3.name, "Bill");
    strcpy(person4.name, "Tim");
    strcpy(person5.name, "Andrew");
    strcpy(person6.name, "Sarah");
    
    strcpy(person1.secondName, "Smith");
    strcpy(person2.secondName, "Johnson");
    strcpy(person3.secondName, "Brown");
    strcpy(person4.secondName, "Williams");
    strcpy(person5.secondName, "Jones");
    strcpy(person6.secondName, "Garcia");
    
    person1.age = 20;
    person2.age = 25;
    person3.age = 30;
    person4.age = 35;
    person5.age = 40;
    person6.age = 45;
    
    Person array1[3];
    Person array2[3];
    
    array1[0] = person1;
    array1[1] = person2;
    array1[2] = person3;
    
    array2[0] = person4;
    array2[1] = person5;
    array2[2] = person6;
    
    Person *arrayMain[2];
    
    arrayMain[0] = array1;
    arrayMain[1] = array2;
    
    printA(arrayMain);
}

运行修正后的代码,会按正确顺序输出:

here

John
Will
Bill
DONE Array

Tim
Andrew
Sarah
DONE Array

内容的提问来源于stack exchange,提问作者user5591905

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:20:27