[英]Why does my char array not print anything?
In c I am trying to assign a char array inside a struct with a user provided value, here is my code:在 c 中,我试图用用户提供的值在结构内分配一个 char 数组,这是我的代码:
#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.问题是name
由于某种原因没有打印,但年龄却按预期打印。
Why is the name
not printing correctly?为什么name
打印不正确?
x->name[20] = arr[20];
sizeof
最好使用对象而不是sizeof
中的类型malloc
始终检查malloc
的结果You need to copy the string using strcpy
function您需要使用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;
}
https://godbolt.org/z/vKddb4b9a https://godbolt.org/z/vKddb4b9a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.