【发布时间】:2019-01-11 11:53:38
【问题描述】:
我以为我终于在 C 语言中有所收获,但在这方面遇到了障碍。我刚刚花了最后 30 分钟寻找可能的解决方案,其中一些涉及 memcpy 和 strcpy 等,但似乎没有一个可以解决我的问题。可能是我没有正确使用它们。
我创建了一个基本程序来说明我的问题。我希望看到如何修复这部分代码将帮助我更好地了解我哪里出错了。
#include <stdio.h>
#include <stdlib.h>
//The program is trying to attempt to give 'test[0] a value of 255'
int main(int argc, char ** argv)
{
//example variables
int height = 4;
int width = 4;
unsigned char image[width][height];
char *test;
//gave the 0th element a basic value
image[0][0] = 255;
//prints out 'Image = 255' as expected
printf("Image = %d\n", image[0][0]);
//allocate test some memory
test = malloc(height * width * sizeof(char));
//Now the problems..
//attempt to give test[0] the value of image[0][0]
test[0] = image[0][0];
//prints out '-1'
printf("Test = %d\n", test[0]);
}
【问题讨论】:
-
在 SO 中询问 30 分钟是否足够值得商榷。另一方面,提供 MCVE 来证明您的问题非常棒,+1。
-
最好的办法是删除所有
char并使用 stdint.h 中的uint8_t代替。仅对字符串使用char。