【问题标题】:Issue with getting user input into a Dynamic array C将用户输入获取到动态数组 C 的问题
【发布时间】:2019-03-05 18:57:39
【问题描述】:

我似乎无法将用户输入输入到 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

无法弄清楚我的错误。希望得到任何帮助。

谢谢!

【问题讨论】:

  • 你明白char teams[counter][10]; 是一个完全独立的变量定义吗?
  • ...char teams[counter]; 也是如此,一旦退出循环,这个变量就会被销毁?
  • 有很多问题,太多无法解决。不过我会回答你的问题 -- teams 应该是 char * 的数组,而不是 char 的数组。
  • OHhhh,我想我还是个菜鸟,不过我现在明白我的错误了。谢谢大家。

标签: c arrays input


【解决方案1】:

有一些基本错误,尤其是在您对指针和 C 语言概念的理解方面。 "team" 是一个 char 指针数组,而 char teams[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);    
}

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多