【问题标题】:passing array structure as pointer in function and initialize将数组结构作为函数指针传递并初始化
【发布时间】:2020-04-05 11:13:27
【问题描述】:

我在初始化结构数组以通过将其作为指针传递时遇到问题。我试图将计数器与我的结构的大小相乘以在我的下一次初始化中跟踪数组结构地址,但它给了我错误的输出。谁能帮帮我?

这是我的代码:

#include <stdio.h>
#pragma pack(1)

struct student {
    int idnum;
    char name[20];
};

void createStudent(struct student *);

int counter=0;

int main() {

    struct student s[2];
    int choice = 0;

    do {
        printf("\nMENU\n");
        printf("1.] Create student\n");
        printf("2.] Display student\n");
        printf("Enter choice: ");
        scanf("%d",&choice);

        switch(choice){
            case 1: createStudent(s);
                    break;
            case 2: displayStudent(s);
                    break;
        }
    }while(choice !=3);
    return 0;
}

void createStudent(struct student *ptr) {
    if(counter > 1) {
        printf("Array Exceed");
    }else {
        *(ptr + counter*sizeof(struct student));
        printf("The counter: %p\n",*(ptr + counter*sizeof(struct student)));

        printf("Enter ID NUM:");
        scanf("%d",&ptr->idnum);
        fflush(stdin);
        printf("\nEnter NAME:");
        scanf("%s",ptr->name);
        counter++;
    }


}

void displayStudent(struct student *ptr) {
    for(int i=0;i<counter;i++) {
        printf("\nStudent ID NUM: %d\t Student Name: %s",ptr->idnum,ptr->name);
    }
}

【问题讨论】:

  • 只需*(ptr+counter) 将指向结构数组中的下一个元素,无需乘以sizeof(struct student)。另外,为什么不将确切的结构变量直接传递给函数呢?
  • @RahulBharadwaj 因为这是我的学校项目。我的老师想要演示使用指针初始化结构数组以访问结构数组
  • @RahulBharadwaj 我试过 *(ptr+counter) 但它给了我重复的数据?
  • @RahulBharadwaj 我认为问题出在我的显示器上?
  • 如果不检查返回,您将无法正确使用scanf()。见Commandment No. 6 for C Programmers

标签: c function structure pass-by-reference


【解决方案1】:

需要进行两项更改。
(1) 你永远不会增加createStudent 中的指针。所以用ptr += counter替换行*(ptr + counter*sizeof(struct student));
由于ptr 已经是struct student 类型的指针,将其加1 会自动移动到下一条记录。

(2) 在displayStudent 中,您也永远不会使用递增的i。因此,在printf 语句之后,在循环中添加ptr++;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2019-05-03
    相关资源
    最近更新 更多