Home > front end >  Structure issue C (Declaration)
Structure issue C (Declaration)

Time:10-15

lets suppose that we have

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
    int CNE;
}etudiant;
etudiant saisie(){
    etudiant T[5];
    int i,j;
    for(i = 0;i<5;i  ){
        
        printf("Le CNE : ");
        scanf("%d",T[i].CNE);
        
    }
    return T;
}
int main(){
    etudiant e = saisie();
    return 0;
}

i want to have 100 Student so i cant declare 100 student and then put their CNE right ? so what is the easy way to declare them

CodePudding user response:

To make your program meaningful it should be rewritten for example the following way

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int CNE;
}etudiant;

void saisie( etudiant *e, size_t n )
{
    for ( size_t i = 0; i < n; i   )
    {
        printf("Le CNE : ");
        scanf("%d", &e[i].CNE);
    }
}

int main( void )
{
    enum { N = 5 };
    etudiant e[N];

    saisie( e, N );

    return 0;
}

As for your program then at least the function return type is invalid

etudiant saisie();

because the function returns an array that is implicitly converted to a pointer to its first element.

So you need at least to declare it like

etudiant * saisie();

But on the other hand, you may not return a local array with automatic storage duration because it will not be alive after exiting the function. So the returned pointer will be invalid.

If you want to create an array within the function and to return it to the caller you need to allocate it dynamically like for example

etudiant *e = malloc( 5 * sizeof( etudiant ) );

Or in this call

scanf("%d",T[i].CNE)

you need to use a pointer to the data member CNE like

scanf("%d", &T[i].CNE)

CodePudding user response:

One problem is that the return type of the function doesn't match the type of the expression you're trying to return:

etudiant saisie(){
  etudiant T[5];  
  ...
  return T;
}

The expression T has type etudiant [5], which in this context "decays" to type edutiant *. etudiant * is not the same type as etudiant.

A second problem is that C functions cannot return arrays. You cannot declare a C function to return an array type, and because of the decay rule when you try to return an array expression all that gets returned is a pointer to the first element of the array - unfortunately, the array ceases to exist once the function returns.

If you want to declare 100 students, just declare an array of etudiant in main:

#define NUM_STUDENTS 100
...
etudiant arr[NUM_STUDENTS];

If you want a function to modify or initialize the array, pass the array (along with its size!) as an argument to the function:

void saisie( etudiant *arr, size_t arrSize )
{
  for ( size_t i = 0; i < arrSize; i   )
  {
    printf( "Le CNE: " );
    scanf( "%d", &arr[i].CNE );
  }
}

which you would call from main as

saisie( arr, 100 ); 
  • Related