#include<stdio.h>
#include<string.h>
struct employee
{
int id;
char name[20];
float salary;
char addr[];
}*emp;
void get_emp(struct employee **record)
{
printf("\tplease enter details of employee:\n");
printf("id= ");
scanf("%d",(*record)->id);//code to get input value
printf("Name= ");
scanf(" %s",(*record)->name);
printf("salary= ");
scanf("%f",(*record)->salary);
}
int main()
{
get_emp(&emp);
printf("id=%d\n",emp->id); // code to display the value
printf("Name=%s\n",emp->name);
printf("salary=%f\n",emp->salary);
return 0;
}
我有一个结构示例,我想将结构指针传递给函数,而不使用普通变量而只使用指针。如果没有进行哪些更改,函数 get_emp(struct employee ** record)中的参数(双指针)是否是正确的方法?另外如何在函数 get_emp(struct employee ** record)中获取用户的输入值以及如何显示值?
答案 0 :(得分:1)
不需要双指针。您也可以使用单指针完成此操作。但是,在填充结构之前,您需要为结构分配内存。
struct employee *emp = malloc(sizeof(struct employee));
结构中char addr[]
的大小也是未定义的。这需要单独分配,类似于:
emp->addr = malloc(N*sizeof(*emp->addr));
结构中具有固定大小的所有其他字段(如integer,float和20个元素的字符数组)不需要分配。它们的分配将由我们之前做过的malloc完成。但是,由于addr
是指针,因此将为其保留等效于指针大小的内存。要在addr
指向的地址中存储任何内容,我们需要分配。
然后将emp传递给你的函数。删除双指针