【问题标题】:Bug with fprintffprintf 的错误
【发布时间】:2014-03-12 02:19:00
【问题描述】:

编辑:看来我已经修好了...

header[3] = str 
strcpy(header[3], str) 

这些行在使用 printf 时产生相同的输出,但显然 fprintf 只像 strcpy。

这是我的代码:

int pgmWrite( const char **header, const int **pixels, int numRows, int numCols, FILE *out )
{
    int i, j;
    printf("%s\n\n", header[3]);
    for(i = 0; i < 4; i++)
        fprintf(out, "%s", header[i]);      

    printf("success in WRITE\n\n\n\n\n");

    for(j = 0; j < numRows; j++)
    {
        for(i = 0; i < numCols; i++)
            fprintf(out, "%d ", pixels[i][j]);

        fprintf(out, "\n"); 
    }
}

printf 语句中,header[3] 输出为 237。

fprintf 语句中,header[3] 被输出为乱码 unicode 字符。

如果有人想要我可以添加完整程序(300 行)的怪物,如果你真的想看看一切都在做什么......

编辑:这是我发生错误时的输出(所有这些输出都来自上述函数)

P2
# baboon.pgma created by PGMA_IO::PGMA_WRITE.
512  512
s· _    .   .
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0  
 (plus a couple thousand more zeroes for the rest of the image)

FULL CODE FILE 1

FULL CODE FILE 2

TEST IMAGE FILE

产生错误:./a.out -E 75 ./baboon.ascii.pgm testBaboon.pgm

【问题讨论】:

  • 没有人想要完整的程序。我们想要一个能够重现问题的简短程序。
  • 当您说“输出是乱码 unicode 字符”时,您是如何确定的? (提示,notepad.exe 不是确定这一点的可靠方法)你是如何打开 out 的?
  • 我们需要查看FILE* out 的声明,因为鉴于明显的乱码输出,这可能是根本原因之一。
  • 我打开了两种方式。 gedit 和(因为我的输出是一个 .pgm 文件)在照片查看器中。照片查看器无法显示它,当我在 gedit 中打开它时,唯一“搞砸 unicode”的部分是一行。该行指定文件的最大白色“强度”。如果我在程序的其他地方编辑它,我可以完美地打印出新值,直到我尝试打印到文件。
  • 也许header[3] 没问题,header[0] 等有乱码。您必须发布一个创建乱码的完整程序,以便其他人可以重现它。

标签: c printf


【解决方案1】:

编辑:我之前的示例基于 char* 指针数组,这不是 OP 所考虑的(感谢用户 0605002 指出这一点)。

下面是一个快速示例,概述了该问题的简单测试用例。在malloc 之后使用memcpy 可确保我们拥有有效的内存块并防止以后访问期间出现段错误。

#include <iostream>

using namespace std;

#define SIZE 8

int main()
{
    size_t size = sizeof(char*) * SIZE;
    char* test = "Test1234";

    char* *header = (char**) malloc(size);
    memcpy(header, "0", size);
    for(int i = 0; i < SIZE; i++)
    {
        header[i] = (char*) malloc(size);
        memcpy(header[i], "0", size);  
    }

    header[0] = test;
    header[1] = "abc";

    FILE * pFile;
    pFile = fopen("myfile.txt", "w");

    for(int i = 0; i < SIZE; i++)
        fprintf(pFile, "%s\n", header[i]); 

    fclose (pFile);

    free(header);

    return 0;
}

【讨论】:

  • 当我将其更改为 fprintf(out, "%s", *header[i]); 时,我遇到了段错误
  • 然后,在该行之前添加一个检查 if(header[i]) 以检查有效内存并确保在该代码运行之前,您的 header 内容一旦被初始化为零。我将在一秒钟内更新我的示例。
  • *header[i] 不是一个 char 吗?使用%s 打印char 可能是segfault 的原因。
  • @0605002 不一定。在我上面的测试用例中,完整的字符串“Test1234”被写入文件。
  • @PhilipAllgaier,是的,没错。但是在您的代码中,header 实际上是一个指向字符的指针数组,因此取消引用 header[i] 将给出一个字符串。但在 OP 中的代码中,header 是一个指向字符的指针,因此不需要取消引用。在那里,header[i] 是一个字符串(指向字符的指针),*header[i] 是一个字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 2016-10-22
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多