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

标签 c pointers dynamic malloc allocation

我正在为一个类编写一个小型 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: %s\n", 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("%s\n", 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: %s\n", cnt, lines[cnt]);
}

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

当然你可以优化这段代码,例如仅对 strlen 进行一次计数,等等

关于c - 为什么我的指针数组在动态分配后被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18293914/

相关文章:

c - ptrace 在 Linux 中如何工作?

c++ - 为什么来自 Bjarne 的 "Tour of C++"的代码有效?

jquery - jqGrid 和动态分组

c - 将指针参数传递给其他文件中的函数

algorithm - 0-1 背包动态规划解法行不通

jquery - 根据星期几添加类(class)

java - 如何在 Java 中表示 TCP 端口范围(16 位)

C 中的 char 数组并进行比较

c - 当用作较大数学表达式的一部分时,使用宏会导致输出不正确 - 为什么会发生这种情况?

c - 请解释一下这背后的概念,(c 编程中的 ptr 和 *ptr)之间的区别