My aim is do declare an array of pointer to my person struct and then use it to modify the name and the age of the persons.I am pretty lost in my code so any help would be appreciated.Thanks!!!
#include <stdio.h>
#define HOW_MANY 7
char *names[HOW_MANY]= {"p1", "p2", "p3", "p4", "p5", "p6", "p7"};
int ages[HOW_MANY]= {2, 1, 16, 8, 10, 3, 4};
struct person
{
char person_name[30];
int person_age;
}*array[10];
static void insert(struct person array[], char *name, int age)
{
static int nextfreeplace = 0;
array[nextfreeplace] = (struct person*) malloc(sizeof(struct person));
&array[nextfreeplace]->person_name = name;
&array[nextfreeplace]->person_age = age;
nextfreeplace++;
}
int main(int argc, char **argv)
{
struct person *array[10];
int index;
int personNumber = 1;
for (index = 0; index < HOW_MANY; index++)
{
insert (array[index], names[index], ages[index]);
}
for (index = 0; index < HOW_MANY; index++)
{
printf("\nPerson number %d has name %s and age %d \n", personNumber,
array[index]->person_name, array[index]->person_age);
personNumber++;
}
return 0;
}
The errors I get:
arrays.c: In function ‘insert’:
arrays.c:20: warning: implicit declaration of function ‘malloc’
arrays.c:20: warning: incompatible implicit declaration of built-in
function ‘malloc’
arrays.c:20: error: incompatible types when assigning to type
‘struct person’ from type ‘struct person *’
arrays.c:21: error: invalid type argument of ‘->’ (have ‘struct person’)
arrays.c:22: error: invalid type argument of ‘->’ (have ‘struct person’)
make: *** [arrays] Error 1
=but ratherstrcpy( destPtr, srcPtr);to use ANY system function, the appropriate header file must be part of the source via: `#include <stdio.h> #include <stdlib.h> #include <string.h> etc. read the man page for each system function used to see what header file is required (and perhaps what #define is needed before the #include of the header file)insert()function, how is main() to know if the operation was successful or not? code needs to check (!=NULL) the returned value from malloc() to assure the operation was successful. Suggest returning some indicator/status frominsert()that main() can check to assure the insert operation was successful. main() needs to pass all the malloc'd memory pointers tofree()to avoid a memory leak