So I basically have a struct with a name, which has to be dinamically, and an ID. I think it can look like this.
typedef struct {
char *name;
unsigned int id;
} person;
Now I shall write a function with the given start:
person *readData();
Both the struct and the name have to be dinamically, I want to do this with the malloc function. For all persons there should also be an array, let's name it "people[1000]".
Here are is my try on the said function with the main function:
int count = 0;
person *readData() {
int i, len;
char puffer[1000];
printf("Name: ");
scanf_s("%999s", &puffer);
len = strlen(puffer);
people[count].name = (char *)malloc((len + 1)*sizeof(char));
for (i = 0; i < len; i++)
people[count].name[i] = puffer[i];
people[count].name[len] = '\0';
}
void main(void)
{
person *people[1000];
readData();
printf("\n%s\n", people[count].name);
}
Well, it doesn't seem to work that way. Visual Studio says in the function, that "people" has to be of type union or struct. Any quick input? It's just basic C since I am at the start of learning it.
EDIT: Full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name;
unsigned int id;
} person;
person people[1000];
int count = 0;
person *readData() {
int i, len;
char puffer[1000];
printf("Name: ");
scanf_s("%999s", &puffer);
len = strlen(puffer);
people[count].name = (char *)malloc((len + 1)*sizeof(char));
for (i = 0; i < len; i++)
people[count].name[i] = puffer[i];
people[count].name[len] = '\0';
}
void main(void){
readData();
printf("\n%s\n", people[count].name);
}
people) is local to themain()function, so it's impossible forreadData()to know about it without you passing it (or making it global). You probably didn't meanperson *readData()butvoid readData(person* people). Your code contains a lot of other problems too though.