i have a structure called person on header file:
typedef struct person
{
int age;
char name[42];
char *surname;
} t_person;
Also, i have two function: The first function, called by main, return a void* pointer to a strucutre of dimension equal to t_person dim. The second function is called setName and take in input the void* pointer to struct and a pointer to char.
This is the main function:
#define STRING_LEN 100
int main()
{
void* person = createPerson();
// variables for testing
int testNumber = 1;
int number = 42;
int result=0;
int number2=0;
char *string = (char *)malloc((sizeof(char) * STRING_LEN));
strncpy(string,"Marco", STRING_LEN);
setName(&person, string);
}
and this is the .c file:
#include "function.h"
#include <string.h>
void* createPerson()
{
void* newPerson=malloc(sizeof(struct person));
return newPerson;
}
void setName(void* person, char *name)
{
t_person* person_pt = (t_person*)person;
for(int i=0;i<strlen(name);i++)
{
person_pt->name[i]=name[i];
}
printf("str: %s \n", person_pt->name[i]);
}
I want to set person->name but my code don't work. it fill the struct field name but it is always full of trash. I think that the problem is that i dont understand something about pointer.
createPerson()returnvoid*instead oft_person*?&personshould just beperson, sincepersonis already a pointer.