0

I want to create a function to initialize values of structure like that :

// main.c
#include <stdio.h>
#include <stdlib.h>
#include "main.h"

int main(int argc, char *argv[]){
    int i, taille = 2, cmpt = 0;
    Personne joueur[2];

    for(i = 0; i < taille; i++){
        initialiserJoueur(&joueur[i]);
    }

    printf("\n%s %s : %d\n", joueur[0].nom,joueur[0].prenom, joueur[0].age);

    return 0;
}

void initialiserJoueur(Personne *joueur){
    joueur->age = 0;
    joueur->nom = "";
    joueur->prenom = "";
}
// main.h
typedef struct Personne Personne;

struct Personne {
    int age;
    char nom[100];
    char prenom[100];
};

void initialiserJoueur(Personne *joueur);

in function "initialiserJoueur", the fields "nom" and "prenom" won't initialize and are red underline, an idea ?

2
  • There's perhaps an error message coming along with the red underlining Commented Nov 27, 2021 at 16:04
  • Hello, yes "The expression must be a changeable value" Personne *joueur Commented Nov 27, 2021 at 16:06

1 Answer 1

1

Arrays can't be assigned to directly. You need to use strcpy to write to one:

joueur->nom = strcpy("");
joueur->prenom = strcpy("");

Or even simpler, since you're setting all fields to 0, just initialize the array that way:

Personne joueur[2] = { { 0 } };
Sign up to request clarification or add additional context in comments.

5 Comments

More specifically a string literal in C is a pointer, so char str[80] = "text"; is not valid - I hope someone can expand on this I have got to dash out right now.
Thanks for your answer, if i initialize with 0 value, the strings types will at blank ?
@B.Christophe Yes, the char arrays will be initialized with all bytes 0.
@Rodney That's valid because it's an initializer. char str[80]; str = "text"; is not valid.
@dbush Thanks for the correction - I confirmed you are right with my compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.