2017-04-25 55 views
0
#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; 
} 

我已經試過:'人*插入(INT * NUM)如何通過引用返回一個結構數組?

和它的作品,但怎麼能傳遞一個數組引用`

這PROGRAMM應該問他有多少人你要不要?插入(在函數中插入)和用for,他應該問名字,姓氏,年齡。

插入後,他應該打印,但爲了快速,我會嘗試數組(結構)的第一個元素(索引)。

+2

C沒有引用或傳遞通過引用。所有函數參數都是按值傳遞的,只能返回值。但是,您可以傳遞指針(按值)或返回指針,這些指針具有相似的效果。 –

回答

3

您不能從函數中返回整個數組,但可以返回數組的基本位置。例如,你可以這樣做:person *insert(int *sz);。但是我在你的代碼中看到你正在傳遞&p&num變量到插入方法中,也許你想在該函數中修改它們,然後在main()中對它進行處理。爲此,我會提供以下建議:

  1. 更換線16 person pperson *p。由於p應該保存數組的基值。記住數組名稱只不過是列表中第一個元素的基地址。
  2. 更改您的功能定義以接收person**而不是person*。既然你想修改一個指針變量,因此你需要一個指向變量的指針。像這樣改變它:`void insert(person ** p,int * num)
  3. 使用後釋放內存;在main的結尾添加一個free(p)

`