编辑:好吧,看来我已经修复了它......
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)
产生错误:./a.out -E 75 ./baboon.ascii.pgm testBaboon.pgm
最佳答案
编辑:我之前的示例基于 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;
}
关于c - fprintf 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340710/