【发布时间】:2017-04-25 16:25:55
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data{
char name[20];
char lastname[25];
int age;
}person;
void insert(person *p,int *num);
int main()
{
int num;
person p;
insert(&p,&num);
printf("Name: %s",p[0].nome); /* Here i would print the first struct by
my array, but: is not array or not pointer Why?? */
}
void insert(person *p, int *num)
{
int dim;
person *arr;
printf("Insert how many people do you want? "); /* How many index the
array should have */
scanf("%d",&dim);
arr = (person *) malloc(dim*sizeof(person)); /* I'm not sure for
this explicit cast. */
for(int i = 0; i < dim; i++)
{
printf("Insert name: ");
scanf("%s",arr[i].name);
printf("Insert lastname: ");
scanf("%s",arr[i].lastname);
printf("Insert age:': ");
scanf("%d",&arr[i].age);
}
*num = dim;
*p = *arr;
}
我试过了:`person *insert(int *num)
它的工作原理,但如何传递一个数组引用?`
这个程序应该问你想插入多少人(在函数 insert 中),并且用 for,他应该问姓名、姓氏、年龄。
插入后,他应该打印,但为了快速,我会尝试使用数组(结构)的第一个元素(索引)。
【问题讨论】:
-
C 没有引用或传递引用。所有函数参数都按值传递,并且只能返回值。但是,您可以传递指针(按值)或返回指针,这具有类似的效果。