asdasdasd1234 asdasdasd1234 - 4 months ago 20
C Question

array of structs and malloc [C]

I have a problem with this code. I want to code a program that has various personal info in an array. And I want 15 Arrays to be set up in one place in the memory (malloc).
Also the programm should output (printf) the personal info of one person on request (angestellter[0 - 14]).

The Code Errors I recive are the following:


gcc ANGDB.c
ANGDB.c: In function ‘print_angestellter’:
ANGDB.c:14:18: error: subscripted value is neither array nor pointer nor vector
nu = angestellter[x].nummer;
^
ANGDB.c:15:18: error: subscripted value is neither array nor pointer nor vector
vn = angestellter[x].vorname;
^
ANGDB.c:16:18: error: subscripted value is neither array nor pointer nor vector
nn = angestellter[x].nachname;
^
ANGDB.c: In function ‘main’:
ANGDB.c:25:13: error: subscripted value is neither array nor pointer nor vector
angestellter[0] -> nummer = 1;
^
ANGDB.c:26:13: error: subscripted value is neither array nor pointer nor vector
angestellter[0] -> vorname = "George";
^
ANGDB.c:27:13: error: subscripted value is neither array nor pointer nor vector
angestellter[0] -> nachname = "Washington";



This is my code:

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

struct angestellter{
int nummer;
char vorname[50];
char nachname[50];
}angestellter;

void print_angestellter(int x){
int nu;
char vn[50];
char nn[50];
nu = angestellter[x].nummer;
vn = angestellter[x].vorname;
nn = angestellter[x].nachname;
printf("%d, %s, %s\n", nu, vn, nn);
}

int main(){
struct angestellter **db = malloc(sizeof(angestellter)*15);
angestellter[0] -> nummer = 1;
angestellter[0] -> vorname = "George";
angestellter[0] -> nachname = "Washington";
print_angestellter(0);
}

Answer

Where you're using angestellter, which is a single instance of struct angestellter, you should be using db, which is your dynamically allocated array. You should also declare it as struct angestellter * instead of struct angestellter **. This will also need to be passed to print_angestellter.

You also need to use strcpy to copy strings. You can't directly assign a string to a character array.

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

struct angestellter{
    int nummer;
    char vorname[50];
    char nachname[50];
};

void print_angestellter(struct angestellter *db, int x){
    int nu;
    char vn[50];
    char nn[50];
    nu = db[x].nummer;
    strcpy(vn, db[x].vorname);     // use strcpy to copy strings
    strcpy(nn, db[x].nachname);
    printf("%d, %s, %s\n", nu, vn, nn);
}

int main(){
    struct angestellter *db = malloc(sizeof(struct angestellter)*15);
    db[0].nummer = 1;
    strcpy(db[0].vorname, "George");
    strcpy(db[0].nachname, "Washington");
    print_angestellter(db, 0);
}
Comments