【问题标题】:Using pointers to input in a struct使用指针在结构中输入
【发布时间】:2014-01-16 12:24:55
【问题描述】:

我试图从用户那里得到一些输入到这个函数中的结构:

void adding(){
    Item *x = malloc(sizeof(Item));
    printf("Enter an integer.");
    scanf("%d", (x->any));
    printf("Enter a string.");
    scanf("%s", (x->text));
    printf("Which set would you like to add the Item to A/B?");
    while((scanf("%c", inp)) != ("A"||"B")){
        printf("Set does not exist\n");
    }
        if(A == inp)
            add(A, *x);
        else
            add(B, *x);

}

Item结构如下:

typedef struct anything{
    char text[MAXI];
    int any;
}Item;

最后调用的add函数就是这个:

void add(Array *S,Item *x){
    bool rep = false;
    int i = 0;
    for(i = 0; i<(S->size); i++){
        if(compStructs(x,S->arr+i))
            rep = true;
    }
    if(rep == false){
            Item *p2 = realloc(S->arr, (S->size+1)*sizeof(Item));
            *p2 = *x;
            (S->size)++;
    }
    else
        printf("The item is already in the set.");

}

由于遇到第一个 scanf() 时发生运行时错误,我认为我在处理指针的方式上做错了。

【问题讨论】:

  • 开启编译器警告。还要考虑scanf() 如何修改它的参数。此外,不要使用scanf(),这是错误的和邪恶的。使用fgets()fgetc() 获取用户输入,使用strtol()strtod()strtok_r()strchr()strstr() 进行解析。

标签: c pointers input struct


【解决方案1】:

编译时包含所有警告和调试信息(例如gcc -Wall -g)。学习使用调试器(例如gdb)。

那么,你应该使用scanf(3) 的结果。它给出了真正阅读的项目的数量。

while((scanf("%c", inp)) != ("A"||"B")) 是非常错误的。我相信编译器会警告你的!

应该是

char inp = 0;
while (((inp=0),scanf(" %c", inp) == 1) && inp !=  'A' && inp != 'B')

【讨论】:

    【解决方案2】:

    首先 scanf 应该给出一个运行时错误。 scanf 期望一个变量的位置,其中将从用户读取的值放置在其中。

    你应该写scanf("%d", &amp;(x-&gt;any));而不是scanf("%d", (x-&gt;any));

    因为当您通过 malloc 分配内存时,所有字节都将被分配 value = 0。

    所以基本上写scanf("%d", (x-&gt;any));你是说把从用户读取的值放到内存位置0。这是错误的。

    我在您的代码中发现的另一个错误是您调用 add() 函数时。

    它期望Item * 作为第二个参数。而当您通过add(A, *x);add(B, *x); 调用它时,您传递的是Item 而不是Item *。 bcz x 本身是一个Item * 类型变量。所以你应该这样称呼它add(A, x);

    干杯:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多