In c I am trying to assign a char array inside a struct with a user provided value, here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char name[20];
int age;
};
struct person *assign(char arr[], int age)
{
struct person *x = malloc(sizeof(struct person));
x->name[20] = arr[20];
x->age = 21;
return x;
}
int main()
{
char name[20] = "Arthur morgan";
int age = 34;
struct person* person1 = assign(name, age);
printf("name: %s\n", person1->name);
printf("age: %d\n", person1->age);
return 0;
}
The problem is that the name
prints nothing for some reason, the age however prints as expected.
Why is the name
not printing correctly?
CodePudding user response:
x->name[20] = arr[20];
- It does not copy the array
- It copies 1 character and you are accessing array outside its bounds which is undefined behaviour (UB)
- It is better to use objects not types in
sizeof
- Always check the result of
malloc
You need to copy the string using strcpy
function
struct person *assign(char arr[], int age)
{
struct person *x = malloc(sizeof(*x));
if(x)
{
strcpy(x->name,arr);
x->age = 21;
}
return x;
}