如何在函数中使用结构变量从用户读取数据

时间:2018-12-08 19:19:14

标签: c eclipse gcc struct

我是一个完全的新手。当我运行程序并输入数据时,throw函数仅正确显示整数值,但不显示字符。

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

struct student_data{
    char name[20],department[10];
    int roll_num[0];
};
void collect(struct student_data data);
void throw(struct student_data student1);
int main(void){
    struct student_data student1;
    collect(student1);
    throw(student1);
    return 0;
}
void collect(struct student_data data1){
    printf("Enter name:");
    scanf(" %s",data1.name);
    printf("Enter department:");
    scanf(" %s",data1.department);
    printf("Enter roll number:");
    scanf(" %d",data1.roll_num);
}

void throw(struct student_data student1){

    printf("%s\n",student1.name);
    printf("%s\n",student1.department);
    printf("%d\n",student1.roll_num[0]);
}

2 个答案:

答案 0 :(得分:0)

为了在函数collect()中修改传递给它的数据,您需要传递对数据的引用,而不是对数据本身的引用。有关如何执行此操作的想法,请参见accepted answer。 因此,您将进行以下更改:

使用void collect(struct student_data *data)代替void collect(struct student_data data),并在main()中使用collect(&student1)代替collect(student1)

您对roll_num的使用有点狡猾,因此我忽略了它。下面是代码相关部分的修改版本:

int main(void){
   struct student_data student1;
   collect(&student1);
   throw(student1);
  return 0;
}
void collect(struct student_data *data1){
    printf("Enter name:");
    scanf(" %s",data1->name);
    printf("Enter department:");
    scanf(" %s",data1->department);
//    printf("Enter roll number:");
//    scanf(" %d",data1->roll_num);
}

答案 1 :(得分:0)

您应该知道,在C编程语言中,参数是通过值传递的。当您在主函数中将结构实例创建为struct student_data student1;并将其传递给函数collect()throw()时,您只是将其作为值传递,这意味着将创建该值该实例在函数中的副本,当销毁该函数时,该副本也将被销毁,并且永远不会影响您在主函数中创建的真实实例。为了防止这种情况,您需要使用指针。检查下面的代码;

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

struct student_data{
    char name[20],department[10];
    int roll_num;
};

void collect(struct student_data *data);
void throw(struct student_data *student1);

int main(void){
struct student_data *student1;
collect(&student1);
throw(&student1);
return 0;
}

void collect(struct student_data *data1){
    printf("Enter name:");
    scanf(" %s",&data1->name);
    printf("Enter department:");
    scanf(" %s",&data1->department);
    printf("Enter roll number:");
    scanf(" %d",&data1->roll_num);
}

void throw(struct student_data *student1){

printf("%s\n",student1->name);
printf("%s\n",student1->department);
printf("%d\n",student1->roll_num);


}