简体   繁体   English

为什么我不能在IF-Else中声明char数组?

[英]Why Can't I declare char array in IF-Else?

I am trying to give the size of a Char array inside if-else depending upon the number of lines in the file. 我试图在if-else中给出一个Char数组的大小,具体取决于文件中的行数。 But when I try to use it afterwards, it gives error: "array undeclared" 但是当我之后尝试使用它时,它会出错:“array unclared”

FILE *f=fopen("G:\\workspaceC\\small1.txt","r");

while((c=fgetc(f))!=EOF)
{
    if(c=='\n')
        no_of_lines++;
}
printf("no_of_lines:  %d",no_of_lines);
int fclose(FILE *f);

if(no_of_lines<10){
    char b[30];
}
else if(no_of_lines>10 && no_of_lines<15){
    char b[60];
}
else{
    char b[106];
}

 for(z=0;z<size;z++)
    {
        if(c==b[z])  ///////Here it gives error: "b undeclared"
        {
            flag=1;
            break;
        }
    }

Array declared within a if block will become local within the block. if块中声明的数组将在块中变为本地。 In technical terms its scope is limited to the if block only. 在技​​术方面,其范围仅限于if块。 That is why you get the error. 这就是你得到错误的原因。 Move the declaration outside the block. 将声明移到块外。

There are more problems though: 但是还有更多问题:

  1. You read the whole file first to decide the number of lines and throw away all the data you read. 您首先读取整个文件以确定行数并丢弃您读取的所有数据。
  2. Where are you initializing the array contents? 你在哪里初始化数组内容? You will end up with problems because of that. 因此,你最终会遇到问题。

Therefore better thing is to use file API to find the file size first, dynamically allocate space for that, read the content into the dynamically allocated space and process the data appropriately. 因此,更好的方法是首先使用文件API查找文件大小,为此动态分配空间,将内容读入动态分配的空间并适当地处理数据。

You have declared the array b in the if block. 您已在if块中声明了数组b So, it is only visible to if block. 所以,它只对if块可见。 And, it cannot be visible outside the if block. 而且,它在if块之外是不可见的。

If you change the code as follow, you will achieve what you want. 如果您更改代码如下,您将实现您想要的。

int size;
if(no_of_lines<10){
    size = 30;
}
else if(no_of_lines>10 && no_of_lines<15){
    size = 60;
}
else{
    size = 106;
}
char b[size];

----> In the IF-ELSE statement, allocate memory instead of declaring the array. ---->IF-ELSE语句中,分配内存而不是声明数组。

  1. char *arr char * arr
  2. malloc((sizeof(char)*30/60/106)

You declared your array in a block code {}. 您在块代码{}中声明了您的数组。 Regardless whether this block is in if statement or not, you can access this array only in this block. 无论此块是否在if语句中,您只能在此块中访问此数组。

If you want to dynamically change the size of the array, declare on a pointer at the beginning of the function and then dynamically allocate memory for it (eg, using malloc). 如果要动态更改数组的大小,请在函数开头的指针上声明,然后为其动态分配内存(例如,使用malloc)。 However, it seems that in you case, you can just declare on the array and give it the maximal size you will need. 但是,在您的情况下,您似乎可以在数组上声明并为其提供所需的最大大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM