c-为什么我的指针数组在动态分配后被覆盖



我正在为一个类编写一个小C程序,该类从文件中读取行,然后使用qsort对它们进行排序。长话短说,我正在为文件的每一行动态分配内存,存储为char*数组中的char*。读取和存储表面上根据输出运行良好(见下文),但当我打印出这些行时,它们都是文件中最后一行的副本。有人能指出我(很可能是显而易见的)错误吗?

以下是我目前遇到的问题的相关代码:

char* trim_white_space(char* str);
char* get_line(FILE* infile, char temp[]);
int main(int argc, char* argv[]) {
    FILE* infile; 
    char* input_file = argv[1];
    int cnt = 0;
    char temp[MAX_LINE_LENGTH]; //to hold each line as it gets read in 
    char* tempPointer = temp;
    if (argc < 2) {
        printf("No input file provided");
        return EXIT_FAILURE;
    }
    //determine the number of lines in the file
    infile = fopen(input_file, "r");
    int num_lines_in_file = num_lines(infile);
    fclose(infile);
    //allocate pointers for each line
    char** lines = (char**) malloc(num_lines_in_file * sizeof(char*));
    //temporarily store each line, and then dynamically allocate exact memory for them
    infile = fopen(input_file, "r");
    for (cnt = 0; cnt != num_lines_in_file; cnt++) {
        tempPointer = get_line(infile, temp);  
        lines[cnt] = (char*) malloc(strlen(tempPointer) + 1);
        lines[cnt] = trim_white_space(tempPointer);
        printf("%d: %sn", cnt, lines[cnt]);
    }
    fclose(infile);
    //print the unsorted lines (for debugging purposes)
    printf("Unsorted list:n");
    for (cnt = 0; cnt != num_lines_in_file; cnt++) {
        printf("%sn", lines[cnt]);
    }
char* get_line(FILE* infile, char temp[]) {
    fgets(temp, MAX_LINE_LENGTH-1, infile);
    char* pntr = temp;
    return pntr;
}
char *trimwhitespace(char *str)
{
  char *end;
  // Trim leading space
  while(isspace(*str)) str++;
  if(*str == 0)  // All spaces?
    return str;
  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;
  // Write new null terminator
  *(end+1) = 0;
  return str;
}

我有这个示例输入文件5-1input.dat:

Hi guys
x2 My name is
Slim Shady
For real

这是我得到的输出:

user@user-VirtualBox ~/Desktop/Low-level/HW5 $ ./homework5-1 5-1input.dat 
0: Hi guys
1: x2 My name is
2: Slim Shady
3: For real
Unsorted list:
For real
For real
For real
For real

在注释中,您应该将循环更改为:

for (cnt = 0; cnt != num_lines_in_file; cnt++) {
    tempPointer = get_line(infile, temp);  
    lines[cnt] = (char*) malloc(strlen(tempPointer) + 1);
    strncpy(lines[cnt], trim_white_space(tempPointer), strlen(tempPointer)+1);
    printf("%d: %sn", cnt, lines[cnt]);
}

strncpy中的大小基于您使用过的malloc的大小。

当然,你可以优化这个代码,例如只计算一次strlen,等等。

相关内容

  • 没有找到相关文章

最新更新