gpt4 book ai didi

c - 具有可变成员大小的结构

转载 作者:行者123 更新时间:2023-11-30 16:23:20 25 4
gpt4 key购买 nike

我想编写函数来获取和打印用户输入的数据。想法是将名字和姓氏作为指针,指向可变大小字符串的指针。代码有什么问题?我究竟做错了什么?替代品?

#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
char *lastname;
int marks[5];
} Student;
void setS(Student *s);
void getS(Student *s);

int main()
{
Student st;
getS(&st);
setS(&st);
return 0;
}

void setS(Student *s){
int i;
printf("Name: %s\t", s->name);
printf("last Name: %s\t", s->lastname);
for(i=0; i<5; i++)
printf("%3d", s->marks[i]);
printf("\n");
}
void getS(Student *s){
int i;
printf("Enter name\n");
gets(s->name);
printf("Enter last name\n");
gets(s->lastname);
printf("Enter marks\n");
for(i=0; i<5; i++)
scanf("%d", &s->marks[i]);
printf("\n");
}

最佳答案

What is wrong with code? What am I doing wrong?

gets(s->name); 尝试将用户输入读取到 s->name 中。 s->name 是尚未分配的 char *gets() 尝试将数据保存到谁知道在哪里?结果:未定义的行为 (UB)。

Alternatives?

读入缓冲区,然后为副本分配内存。

提示:尽可能避免使用 scanf()、gets() 进行用户输入,而使用 fgets()C - scanf() vs gets() vs fgets() .

<小时/>

一些提供想法的代码。

#define NAME_N 100

// return 1 on success
// return EOF on end-of-file
// return 0 other errors
int getS(Student *s) {
*s = (Student) {NULL, NULL, {0}}; // pre-fill with default values.

char buffer[NAME_N];
printf("Enter name\n");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return EOF;
}
trim(buffer);
if (!validate_name(buffer)) {
return 0;
}
s->name = strdup(buffer);

printf("Enter last name\n");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return EOF;
}
trim(buffer);
if (!validate_name(buffer)) {
return 0;
}
s->lastname = strdup(buffer);

printf("Enter marks\n");
for (int i = 0; i < 5; i++) {
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
return EOF;
}
if (sscanf(buffer, "%d", &s->marks[i]) != 1) {
return 0;
}
}
return 1;
}

trim() 是修剪前导/尾随/过多空格的函数。另请参阅How do I trim leading/trailing whitespace in a standard way? .

strdup() 不是 C 标准,但非常常用的字符串复制函数,用于分配内存和复制。 Sample code

validate_name() 是占位符代码,用于确保名称的合理性。在可以接受的事情上要慷慨。名称中通常可接受的字符包括[A-Z、a-z、'-'、'''、' '、'.'] 和许多其他:What are all of the allowable characters for people's names? .

示例:

// Fail a zero length name or one with controls characters in it.
bool validate_name(const char *name) {
if (*name == '\0') return false;
while (*name) {
if (iscntrl((unsigned char) *name)) return false;
name++;
}
return true;
}

关于c - 具有可变成员大小的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54029147/

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