[英]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: 但是还有更多问题:
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
语句中,分配内存而不是声明数组。
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.