Jetson
Jetson

Reputation: 25

How to return an array of structure by reference?

#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;
}

I've tried: `person *insert(int *num)

And it's works,but how can pass an array reference?`

This programm should ask how many person do you want to insert ( in function insert) and with a for, he should ask name,surname,age.

After the insert, he should print, but for quick, i would tried with first element (index) of array (structs).

Upvotes: 0

Views: 380

Answers (1)

Rohan Kumar
Rohan Kumar

Reputation: 5892

You can't return entire array from the function, but you can return the base location of the array. For example you can do like this : person *insert(int *sz);. But i see in your code you're passing &p and the &num variable into the insert method, maybe you want to modify them within that function and manipulate it afterwards in your main(). For that i would have these recommendations:

  1. Change Line 16 person p to person *p. Since p is supposed to hold base value of an array. Remember array name is nothing but a base address to the first element of the list.
  2. Change your function definition to recieve person** rather than person*. Since you want to modify a pointer variable and therefore you'd need a pointer to a pointer variable. Change it like this:` void insert(person **p, int *num)
  3. Free the memory after usage; add a free(p) at the end of main.

`

Upvotes: 3

Related Questions