【问题标题】:Assigning an array element values not working as expected分配数组元素值未按预期工作
【发布时间】: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

标签: c arrays pointers memory


【解决方案1】:

改变这个:

char *test;

到这里:

unsigned char *test;

因为您希望目标数组与源数组的类型相同。

Live Demo

PS:charusually(@Bodo 评论)默认为signed char,其中 255 的结果为 -1。

【讨论】:

  • char 默认是有符号还是无符号由实现定义。许多系统使用签名的默认类型。见stackoverflow.com/questions/17097537/…
  • 哇,谢谢你,不敢相信我什至没有考虑到这一点。直到现在我完全忽略了 unsigned 的含义。感谢您的帮助,在研究问题时,我肯定走错了路..
  • @AspiringNewbie 欢迎您!签名很重要,所以请确保您下次不会忽略它! :)
  • @Bodo 我不知道,谢谢!答案有所改善。不过,我觉得这个Is char signed or unsigned by default?更好,希望你能同意。
【解决方案2】:

您已将test 定义为指向char 的指针。但是,您将unsigned char 分配给char([显然] [在您的环境中] 默认为signed),因此255 表示为-1。试试这个:

int main(int argc, char ** argv)
{
    //example variables
    int height = 4;
    int width = 4;
    unsigned char image[width][height];
    unsigned 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));

    //attempt to give test[0] the value of image[0][0]
    test[0] = image[0][0];

    //now prints out '255'
    printf("Test = %u\n", test[0]);
}

【讨论】:

  • 非常感谢你们,你们为我节省了更多令人沮丧的时间来谷歌搜索错误的东西,希望能修复它。真正地甚至没有考虑未签名的问题。我希望有一天当我知道更多时,我可以帮助社区作为回报。再次感谢:)
  • 实际上他们将变量定义为char,这与signed charunsigned char都不同。这是 C 语言中的一个奇怪之处,请参见:stackoverflow.com/questions/2054939/…
  • 感谢您指出这一点和链接@Lundin!我将进行编辑以获得更准确的答案。
猜你喜欢
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多