我相信我的问题可能与我初始化字符串的方式有关。但我不确定当我尝试为它赋值时然后继续递增指针时为什么会出现问题。
int read_file( char *file_name )
{
char ch;
char *string = '\0';
FILE *file;
int i = 0;
file = fopen(file_name, "r");//opens the file
if(!file){
return 0;//file not opened
}else{
while((ch = fgetc(file))!= EOF){
if(ch >= 'A' && ch <= 'z'){
string++ = ch;
continue;
}
string = '\0';
}
return 1;
}
return 0; //file not opened
}
答案 0 :(得分:1)
你必须为字符串分配一些内存:
#define MAX_CH 128
char string[MAX_CH];
然后你可以使用它的索引范围从0到127:
string[i] = ch;
你的内循环应该是这样的:
int i = 0;
while( i < MAX_CH && (ch = fgetc(file))!= EOF){
if(ch >= 'A' && ch <= 'z'){
string[i] = ch;
i++;
continue;
}
}
答案 1 :(得分:1)
触发编译器错误的行是:
string++ = ch;
由于string
是一个指针,string++
也是一个指针。此外,因为赋值的LHS上的指针是增量的结果,所以它是一个不可修改的“左值”。你需要:
*string++ = ch;
现在你要指定指针指向的东西(然后递增指针)。
您还遇到问题:
string = '\0';
当你想要的是string = NULL;
(null终止字符串)时,这是一种写string = 0;
或*string = '\0';
(将指针设置为null)的有趣方式。
您仍有问题:string
指向空的且不可修改的字符串文字。你还没有为它分配任何空间。你可以使用这样的东西:
char buffer[256];
char *string = buffer;
然后您需要担心不会溢出您正在使用的缓冲区的末尾。
答案 2 :(得分:0)
两件事: 一,字符串++就像写字符串=字符串+ 1,你不能在作业上做。 你会得到一个错误,说左值必须是可修改的,(string ++)不是可修改的值。
二,在写入内存之前,你必须首先分配它,所以你有两个选择,要么分配足够的内存来包含你的字符串在堆栈上:
char string_buffer[1024];
char *string = &(string_buffer[0]);
或者,您可以使用malloc / realloc方案,但这是一个稍微复杂的代码,类似于:
#define INITIAL_SIZE 64
#define GROWTH_FACTOR 2
char *string_ptr = (char *)malloc(INITIAL_SIZE); // Allocates INITIAL_SIZE bytes.
if (!string_ptr) { /* malloc can return null value, when no memory is available. Handle here. */}
char *string = string_ptr;
// Doing stuff here, string outgrows it's boundaries.
string_ptr = (char *)realloc(string_ptr, INITIAL_SIZE * GROWTH_FACTOR);
if (!string_ptr) { /* malloc can return null values, when no memory is available. Handle here. */ }
最终必须释放Malloc内存,否则您将遇到内存泄漏。
堆栈分配的字符串(char [])不应该返回给调用函数 - 因为当它分配给它的堆栈上的函数返回时它不再“生命”。
无论哪种方式,您都必须使用已分配的内存来构建字符串。