Reputation: 37
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);
}
Upvotes: 1
Views: 99
Reputation: 11061
people
variable is undefined in the body of your readData
function.
That is why the complier fails with error.
You can pass variable to the function person *readData(person *people)
.
Do not forget to change readData();
to readData(people);
in the main
function.
Do not mix pointer notation with array notation if you need just 1-dimensional array.
Use person people[1000];
instead of person *people[1000];
Upvotes: 2
Reputation: 8209
Your function readData doesn't know about your people array. If you rewrite it along these lines:
void readData(person** people) {
your code
}
void main() {
person* people[100];
readData(people);
}
It should go better.
Please see zavgs answer for more things to improve.
Upvotes: 0