gpt4 book ai didi

c - 我的字符串文字发生了什么?

转载 作者:行者123 更新时间:2023-11-30 17:09:54 24 4
gpt4 key购买 nike

使用 GNU cc 4.8.1 为 Atmega64 进行编译。我的字符串文字正在消失。我试图将一个帧从 Atmega64 UART 中推出,除了来自全局数组的有效负载(中间 10 个字节)之外,所有帧都成功推出。如果我写入全局数组

array[0] = 'H';
array[1] = 'e';
array[2] = 'l';
array[3] = 'l';
array[4] = 'o';

这使得它脱离了 UART。但是,如果我使用字符串文字 char *array = "Hello"; 然后将此指针传递给 memcpy(),则该文本永远不会移出 UART,尽管帧的页眉/页 footer 分做。我只是在有效负载/消息应该在的地方得到了垃圾。字符串文字发生了什么,编译器是否因为某种原因将其吹走?我将数组填充到一个函数中,然后立即调用另一个构建 UART 帧的函数,将全局数组内容复制到输出数组中。

这是我将字符串文字复制到全局数组中的函数。

char screen[4][11]

display(void)
{
char *strpt;

LCDmemcpy(1, "stuff"); //doesn't work
strpt = "blah";
LCDmemcpy(2, strpt); //doesn't work either
}

void LCDmemcpy(char seg, char *buff)
{
u8 i;

// if(seg<5 && seg>0)
{
//memcpy(&screen[seg-1][0], buff, 11);
for(i=0; i<11; i++)
{
screen[seg-1][i] = buff[i];
}
}
}

最佳答案

当在函数调用中用作参数时,数组的名称会衰减为指向第一个元素的指针。这将允许将文字(衰减为相同类型)分配给它,这不会修改原始数组(因为指针是按值传递的),但会修改指针参数的值...

此代码说明了您的问题:

#include <stdio.h>

void confusing(char array[])
{
char* literal = "Hallo";
array = literal;
printf("%s - now array points to literal...not...\n", array);
}

int main(void)
{
char myArray[] = "xyz";
confusing(myArray);
printf("%s - as expected, no change here\n", myArray);
return 0;
}

输出:

Hallo - now array points to literal...not...
xyz - as expected, no change here

关于c - 我的字符串文字发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com