【问题标题】:does the array created by malloc() add a '\0' character to the end of the array? [duplicate]malloc() 创建的数组是否在数组末尾添加了一个 '\0' 字符? [复制]
【发布时间】:2016-05-03 05:41:03
【问题描述】:

我有一个代码可以将 txt 文件的内容反向打印为字符串。İ 使用 malloc() 函数将我的字符串的每个字符存储在 txt 文件中。它可以正常工作,但它会打印 with 的内容前面一个'\0'是什么原因?

void veriyitersyazdir(FILE *file)
{
    char metin;          // that gets the every single char of my string
    int boyutsayac=0;    // that stores my string's size
    char *metinarr=NULL; // that is my malloc() array pointer
    int dongusayac;      // that is a counter variable that is used to print my string reversely.

    system("cls");

    file = fopen("C:\\metin.txt", "r");

    do {
        metin = fgetc(file);
        if (metin==EOF) {
            break;
        }

        boyutsayac++;
    } while (1);

    metinarr = (char *) malloc(sizeof(char)*boyutsayac);
    fseek( file, 0, SEEK_SET);
    for (dongusayac = 0; dongusayac < boyutsayac; dongusayac++) {
        metin = fgetc(file);
        metinarr[dongusayac]= metin;
    }

    fseek( file, 0 , SEEK_SET);
    for (; dongusayac >=0; dongusayac--) {
        printf("%c", metinarr[dongusayac]);
    }

    fclose(file);
}

txt文件内容:Mustafa Mutlu

代码的输出:UltuM afatsuM

【问题讨论】:

  • for (; dongusayac &gt;=0; dongusayac--) : dongusayac 以更大的值开头。
  • metin = fgetc(file); where metin is a char 是完全错误的。见stackoverflow.com/questions/35356322/…fgetc 返回一个 int,您应该遵守该合同,因为 char 可能不能代表 EOF(在 char 未签名的系统上)。在带有签名字符的系统上它仍然是错误的,只是有点不同。
  • 这就是为什么你应该总是用英文编写源代码的原因。因为你最终可能需要帮助。

标签: c arrays


【解决方案1】:

正如 bluepixy 所指出的,您的主要问题来自您用来读取的for 循环,该循环使dongusayac 比读取的字符数多一倍。

for 循环中总是如此,因为它增加了变量,然后检查它是否仍然符合条件。所以最后一次增加永远不符合条件。

这是一种更简洁的方式来做你正在做的事情:

void reverse() {
    FILE *file;
    size_t size;
    int i;

    if (!(file = fopen("c:\\metin.txt", "r"))) {
            printf("error opening file\n");
            exit(1);
    }

    fseek(file, 0L, SEEK_END);
    size = ftell(file);

    char *content = malloc(size);           // allocate memory for the full text file
    fseek(file, 0, SEEK_SET);               // rewind the file cursor
    fread(content, 1, size, file);

    for (i = size - 1; i >= 0; i --) {      // output contents in reverse order
            printf("%c", content[i]);
    }

    fclose(file);
}

【讨论】:

  • 我同意,但它肯定不是 '\0'。
  • 变量名太混乱了,我没有注意到。我会更新我的答案以反映这一点。
猜你喜欢
  • 2017-06-16
  • 2017-09-02
  • 2010-12-30
  • 2021-02-07
  • 2021-12-16
  • 2018-12-22
  • 2012-12-03
  • 1970-01-01
  • 2015-06-22
相关资源
最近更新 更多