【问题标题】:Why does this only work with everything in main?为什么这只适用于 main 中的所有内容?
【发布时间】:2014-01-10 22:42:02
【问题描述】:

所以我试图完成这个挑战: http://www.reddit.com/r/dailyprogrammer/comments/1sob1e/121113_challenge_144_easy_nuts_bolts/

我想使用文本文件作为输入。 如果我将正在使用的单独函数的内容复制到 main 中,我的代码就可以工作,否则在调用 readall 或 compare 函数后它似乎没有运行任何东西。这是我目前所拥有的:

#include<stdio.h>
#include<stdlib.h>

//variable declarations
int i;
int n;
struct item *prices;

//function declarations
void readall();
int compare(int i);
int fail();

//structure definitions
struct item{
    char *name;
    int price;
};

//main
int main(int argc,char *argv[]){
    if(fail()){
        printf("Input not found\n");
        return 1;
    }
    else{
        readall();
        for(i=0;i<n-1;i++){
            if(compare(i)){
                printf("%s\n",prices[i].name); //not added price change yet
            }
        }
    }
free(prices);
return 0;
}

//functions
void readall(){
    FILE *input = fopen("input.txt","r");
    int n=0;
    fscanf(input,"%u",&n);
    struct item prices[2*n-1];
    malloc(sizeof(prices));
    for(i=0;i<2*n;i++){
        fscanf(input,"%ms",&prices[i].name);
        fscanf(input,"%u",&prices[i].price);
    }
    fclose(input);
}

int fail(){
    FILE *input = fopen("input.txt","r");
    fclose(input);
    if(input==NULL){
        return 1;
    }
    else{
        return 0;
    }
}

int compare(int i){
    if(prices[i].price==prices[i+n].price){
        return 1;
    }
    else{
        return 0;
    }
return 2;
}

在 valgrind 下运行的附带说明中,我可以看到我显然没有正确处理内存,因此任何关于此的提示和/或任何其他建设性的批评将不胜感激。

【问题讨论】:

  • 您必须编译和链接单独的文件。向我们展示你使用的命令。
  • 如果您在这里找到了解决方案,那将是令人惊讶的! tinyurl.com/so-list
  • @PaulBeckingham 我使用cc -Wall -g NandB.c -o NandB编译它
  • 你提到了多个文件,但我在命令中只看到一个。您有两个问题:上面的代码有缺陷(@James 指出了原因),而您关于多个文件的其他问题需要更多信息 - 例如,另一个文件中有什么,以及您是如何编译/链接它的。
  • 次要:回复:int n=0; fscanf(input,"%u",&amp;n);。最好使用unsigned n=0;fscanf(input,"%d",&amp;n);

标签: c function main


【解决方案1】:

您的 readall 函数有误。您正在做的是在堆栈上创建一个数组,然后在堆上分配一个单独的数组,该数组没有名称,因此永远不会使用和泄漏。试试

Prices = malloc(sizeof(item) * n);

【讨论】:

    【解决方案2】:

    我看到了两个直接的问题:

    1. prices 数组分配在堆栈上,您的后续 使用malloc() 毫无意义。使用这样的东西:

      item* prices = malloc ((2*n-1) * sizeof(struct item));
      
    2. readall() 的范围内,定义一个变量n 遮蔽同名的全局变量。只有本地的n 是 使用fscanf() 填充。然而,后来调用compare(), 访问尚未初始化的全局n

    你应该尝试给变量起有意义的名字,而不是 比inx。至少对带有 a 的变量执行此操作 多于几行代码的有意义的生命周期。 (在我看来, 对于简单的循环,使用单字符变量名是可以的。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多