由于这些指针变量,我的代码崩溃了。他们怎么了?
主要
中的变量声明char* fname = (first_name_length*sizeof(char));
char* lname = (last_name_length*sizeof(char));
char* pfname = &fname[0];
char* plname = &lname[0];
功能
void get_first_name(FILE* fp, int length, char* pfname){
char c;
int i = 0;
int number_of_conversions;
//char* first_name = malloc(length*sizeof(char));
number_of_conversions = fscanf(fp, "%c", &c);
while (!isspace(c)){
pfname[i] = c;
number_of_conversions = fscanf(fp, "%c", &c);
}
}
答案 0 :(得分:0)
char* fname = (first_name_length*sizeof(char));
char* lname = (last_name_length*sizeof(char));
这不是你在C中分配内存的方式。你可以静态分配内存:
char fname[first_name_length]; //This assumes that first_ and last_name_length are
char lname[last_name_length]; //constants
或动态如此:
char* fname = malloc(first_name_length*sizeof(char)); //first_ and last_name_length can
char* lname = malloc(last_name_length*sizeof(char)); //be constants or variables