使用if语句中定义的变量

时间:2013-10-15 13:51:18

标签: c if-statement scope

我正在制作一个逐行处理文本文件的程序,但是文件的第一行是一个int,告诉我文件的长度是多少(标题)。问题是,我正在尝试定义一个数组来存储有关文件其余部分的信息,但我一直在city_info和city_dist上收到一个未定义的错误。知道我错过了什么吗?

以下是代码:

    while(fgets(buffer,MAX_LINE,fp)!=NULL) {
    if(firsttime){
        int num_city = atoi(buffer);
        printf("NUMBER OF CITIES = %d\n",num_city);
        node city_info[num_city]; /*compiler says these are undefined*/
        int city_dist[num_city]; /*compiler says these are undefined*/
        firsttime=FALSE;
    }
    .
    .
    .
    /*rest of code*/

这是我得到的编译器错误:

help.c: In function `main':
help.c:33: warning: unused variable `city_info'
help.c:34: warning: unused variable `city_dist'
help.c:41: error: `city_info' undeclared (first use in this function)
help.c:41: error: (Each undeclared identifier is reported only once
help.c:41: error: for each function it appears in.) 
help.c:42: error: `city_dist' undeclared (first use in this function)

编辑:对于那些说我没有使用变量的人,我后来在代码中使用了它

3 个答案:

答案 0 :(得分:1)

在if-block范围内定义的变量在此范围之外是不可见的。试试这个:

int num_city;
node *city_info = null;
int *city_dist = null;
if(firsttime) {
    num_city = atoi(buffer);
    city_info = malloc(num_city * sizeof(node));
    city_dist = malloc(num_city * sizeof(int));
    // check if malloc actually worked...

    //...
}

//...
// clean up!
if (city_info != null) free(city_info);
if (city_dist != null) free(city_dist);

答案 1 :(得分:0)

如果您正在C89模式下编译(并且没有GCC扩展名),那么这是无效的 但是,如果编译器支持C99模式,则在语句之后(或在任何块中)声明变量是完全合法的。

  

对于那些说我没有使用变量的人,我稍后在代码中使用了它

请注意,您的案例变量num_citycity_info[num_city]city_dist[num_city]具有块范围,您无法在if范围之外访问它们(因为它对其他范围是不可见的)。此外,city_info[num_city]city_dist[num_city]可变长度数组,仅受C99支持

答案 2 :(得分:-1)

您不能在声明下面声明。

int a = 0;

print ("%d", a);

int b = 0; //You can not declare variable here. Some compilers wont allow.