gpt4 book ai didi

c - 为什么 %s 不从链接列表中打印

转载 作者:行者123 更新时间:2023-11-30 18:33:03 26 4
gpt4 key购买 nike

我创建了一个包含字符数组的链表。然后我尝试使用 %s 打印它,但它无法打印。我知道我必须通过添加“\0”来转换字符,以便它可以使用“/0”进行打印。但我不知道为什么。

例如,如果我输入:

Bob 20

它应该打印:

New student created: Bob is 20 years old.

但是:它正在打印(没有“Bob”):

New student created: is 20 years old.

#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() 的字符数组,但我不确定为什么......

#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中不存在的元素。

您应该使用标准 C 函数 strcpy在 header <string.h> 中声明。

例如

strcpy( ptr->name, studentName );

关于c - 为什么 %s 不从链接列表中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com