kk-dev11
kk-dev11

Reputation: 2674

"struct" objects with "for-loop" in C Programming

This code is about 'struct' in C..

I created a struct spieler with the properties name and age.. By using the for-loop I let the user to create the struct objects. they are named as sp[i] --> sp1, sp2 etc.

the problem is the objects are created. But I can use them only inside the for-loop. If I want to get the value of "sp1.name" in main function, it doesn't work. How can I solve it?

struct spieler{
  char name[20];
  int age;
};

void erzeuge();

int main() {

int anzahl = 2;
printf("Anzahl Spielern: ");
scanf("%d",&anzahl);

erzeuge(anzahl);

printf("Es sind %d Spielern",anzahl);
/*for(i;i<anzahl;i++){
    printf("%d.%s",i, sp[i].name);
}*/

getchar();

}

void erzeuge(int anzahl){

int i=0;
for(i;i<anzahl;i++){
    struct spieler sp[i];
    printf("Struct fuer Spieler_%d wurde erzeugt\n", i);
    getchar();
    printf("Name: ");
    scanf("%s",sp[i].name);

    printf("%s\n",sp[i].name);
}

Upvotes: 1

Views: 38874

Answers (3)

FreeCodeVN
FreeCodeVN

Reputation: 166

You should declare sp as a pointer at the global scope, and allocate memory for it inside the function erzeuge using malloc.

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

struct spieler {
    char name[20];
    int age;
};

struct spieler *sp;    // Add this

void erzeuge();

int main() {
    int anzahl;
    printf("Anzahl Spielern: ");
    scanf("%d", &anzahl);

    erzeuge(anzahl);

    printf("Es sind %d Spielern\n", anzahl);

    int i;
    for(i = 0; i < anzahl; i++){
        printf("%d.%s\n", i, sp[i].name);
    }

    if (sp) {
        free(sp);
    }
    getchar();
    return 0;
}

void erzeuge(int anzahl) {
    // Add the following line to allocate memory
    sp = (struct spieler*) malloc(anzahl * sizeof(struct spieler));

    int i;
    for (i = 0; i < anzahl; i++) {
        // Remove the following line because it create an array of "i" elements
        // struct spieler sp[i];
        printf("Struct fuer Spieler_%d wurde erzeugt\n", i);
        getchar();
        printf("Name: ");
        scanf("%s",sp[i].name);

        printf("%s\n",sp[i].name);
    }
}

Upvotes: 1

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

Alternative solution without malloc:

void erzeuge(struct spieler* sp, int anzahl)
{
    ...
}

int main()
{
    int anzahl = 2;

    ...

    struct spieler sp[anzahl];
    erzeuge(sp,anzahl);

    ...
}

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183918

You'd have to return an array of players from erzeuge, something like

struct spieler *erzeuge(int anzahl){
    struct spieler *mannschaft = malloc(anzahl*sizeof(struct spieler));
    int i;
    for(i = 0; i < anzahl; ++i){
        // prompt
        scanf("%18s",&mannschaft[i].name);
        ...
    }
    return mannschaft;
}

Upvotes: 1

Related Questions