我创建了一个包含char数组的链表。然后,我尝试使用%s进行打印,但无法打印。我知道我必须通过添加'\ 0'来转换char,以便可以使用'/ 0'打印。但我不确定为什么。
例如,如果我输入:
鲍勃20
它应该打印:
[创建新学生:鲍勃今年20岁。
但是:它正在打印(没有“鲍勃”):
[创建的新学生:20岁。
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[50];
int age;
struct student *next;
};
struct student *createStudent(char studentName[], int studentAge);
int main(void) {
struct student *studptr;
int myAge;
char myName[50];
scanf("%s %d", myName, &myAge);
studptr = createStudent(myName, myAge);
printf("New student created: %s is %d years old.\n", studptr->name, studptr->age);
free(studptr);
return 0;
}
struct student *createStudent(char studentName[], int studentAge){
struct student * ptr;
ptr = (struct student *)malloc(sizeof(struct student));
ptr->name[50] = studentName[50];
ptr->age = studentAge;
ptr->next = NULL;
return ptr;
}
[注意:我理解下面的代码将起作用并打印正确的名称,在此我添加了一个其他方法来更改名为copyStr()的char数组,但我不确定为什么。...
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[50];
int age;
struct student *next;
};
struct student *createStudent(char studentName[], int studentAge);
void copyStr(char *source, char *target);
int main(void) {
struct student *studptr;
int myAge;
char myName[50];
scanf("%s %d", myName, &myAge);
studptr = createStudent(myName, myAge);
printf("New student created: %s is %d years old.\n", studptr->name, studptr->age);
free(studptr);
return 0;
}
struct student *createStudent(char studentName[], int studentAge){
struct student * ptr;
ptr = (struct student *)malloc(sizeof(struct student));
//we need to translate the char into a string
copyStr(studentName, ptr->name);
ptr->name[50] = studentName[50];
ptr->age = studentAge;
ptr->next = NULL;
return ptr;
}
void copyStr(char *source, char *target){
int i = 0;
while(source[i] != '\0')
{
target[i] = source[i];
i++;
}
target[i] = '\0';
}
数组没有赋值运算符。
此声明
ptr->name[50] = studentName[50];
尝试将指针studentName指向的数组的索引为50的不存在元素分配给数组ptr-> name的不存在元素。
相反,您应该使用在标题strcpy
中声明的标准C函数<string.h>
。
例如
strcpy( ptr->name, studentName );
添加到@Vlad的答案中,复制数组的正确方法是对它们进行迭代,从而选择char数组中的每个元素并将其复制到新位置。 strncpy
与缓冲区溢出检查完全一样,因此比strcpy
更好。
请参阅strcpy文档,其中说:“确保目标指向的数组的大小应足够长,以包含与源相同的C字符串(包括终止的空字符),并且在内存中不应重叠带有来源“
另一方面,如果您要寻找单线作业,则可以执行此操作:
char sample[] = {"randomText"};
char sample2[11] = {"randomText"};