无法将整数写入缓冲区内的偏移量 (char*)

Cannot write integer to an offset within a buffer (char*)

我正在尝试将 unsigned integer 写入我的 C 程序中缓冲区中的特定偏移量。缓冲区是典型的 1 字节 char * 缓冲区。 我正在使用 memcpy 通过一些指针算法来执行此操作,以将 memcpy 目的地指向该缓冲区中的特定偏移量。

代码:

char* ph = (char*) malloc(4096);

//Init buffer with '[=10=]'
memset(ph, '[=10=]', 4096);

//Set int to be written
unsigned int tupleCnt = 4;

//Write to 4th byte offset (int* + 1)
memcpy(((int*) ph) + 1, (void *) &tupleCnt, sizeof(tupleCnt));

但是,这不会向该缓冲区写入任何内容。

这是写入此缓冲区的文件的 hexdump:

0000000 0000 0000 0000 0000 0000 0000 0000 0000
               ^

如果我将其写入第 0 个偏移量,它会起作用:

//Write to 0th byte offset (int* + 0)
memcpy(((int*) ph) + 0, (void *) &tupleCnt, sizeof(tupleCnt));

这是十六进制转储:

0000000 0004 0000 0000 0000 0000 0000 0000 0000
          ^

顺便说一下,我正在使用 fwrite 将此缓冲区写入文件,如果它有任何不同的话。

fwrite(ph, 1, strlen(ph), fp);

我也试过在 char* 指针上使用逐字节递增,它也没有帮助。 例如:

//Write to 4th byte offset (int* + 1)
memcpy(ph + 4, (void *) &tupleCnt, sizeof(tupleCnt));

提前致谢! 或者有没有其他方法可以将 int (或任何数字)值写入 char* 缓冲区?除了 int to string conversation,我真的很想避免。我认为这是太多的开销和天真的方法。 :)

你的问题不在memcpy,而在你写入文件的方式:

fwrite(ph, 1, strlen(ph), fp);

此代码写入 0 个字节,因为 strlen return 从开始到第一个的字节数 '[=13=]' 在您的情况下它为零字节。

strlen(ph) 遇到空字符时将停止计数。 由于您已将缓冲区清零,因此当您在第 4 个字节偏移量上写入时 strlen(ph) returns 为零,但在第一个字节偏移量上写入时则不会。使用 fwrite(ph, 1, 4096, fp);

也可以用这个写整数

int *ih = (int*)ph;
ih[1] = tuplecnt;