gpt4 book ai didi

c - 将用户输入获取到动态数组 C 时出现问题

转载 作者:行者123 更新时间:2023-11-30 16:27:54 26 4
gpt4 key购买 nike

我似乎无法将用户输入放入 C 中的动态数组中。

#include "stdio.h"

int main(void){
int counter = 0;
int x = 1;
int i;
printf("Enter the number of teams playing in the league: \n");
scanf("%d", &i);
char teams[i];
for (counter = 0; counter < i; counter++){
char teams[counter];
printf("Enter team names: \n");
scanf("%s", teams);
}
for (counter = 0; counter < i; counter++){
char teams[counter][10];
printf(" Team %d is %s \n", x, *teams);
x++;
}
}

当我运行此代码时,我得到以下输出,

Enter the number of teams playing in the league: 2

Enter team names: Team1

Enter team names: Team2

Team 1 is Team1

Team 2 is \320\365\277\357\376

Program ended with exit code: 0

无法找出我的错误。希望得到任何和所有的帮助。

谢谢!

最佳答案

存在一些基本错误,尤其是您对指针和 C 语言概念的理解。 “team”是一个 char 指针数组,而 char groups[i] 不太正确;一种正确的方法是为团队名称的集合动态分配内存。通过将下面的代码与您的代码进行比较,我相信您可以发现出错的地方。 PS:我在scanf中使用格式字符“m”为团队名称动态分配内存。

int main(int argc, char **argv){
int counter = 0;
int i, ret;
char **teams;
printf("Enter the number of teams playing in the league: \n");
scanf("%d", &i); // check return value yourself
teams=(char **)malloc(sizeof(char *)*i);
if(NULL==teams) perror("not enough memory"), exit(1);
for (counter = 0; counter < i; counter++){
printf("Enter team names: \n");
ret=scanf("%ms", &teams[counter]);
if(ret<1)//hanndle error. i'll just quit.
exit(-1);
}
for (counter = 0; counter < i; counter++){
printf(" Team %d is %s \n", counter+1, teams[counter]);
free(teams[counter]);
}
free(teams);
}

关于c - 将用户输入获取到动态数组 C 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52578010/

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