gpt4 book ai didi

c - 将字符存储在字符指针中

转载 作者:行者123 更新时间:2023-11-30 15:17:29 26 4
gpt4 key购买 nike

我有一个线程可以一一解析传入的字符/字节。我想将字节序列存储在字节指针中,最后当找到“\r\n”序列时,它应该打印出完整的消息。

unsigned char byte;
unsigned char *bytes = NULL;

while (true){ // thread which is running on the side
byte = get(); // gets 1 byte from I/O
bytes = byte; //
*bytes++;
if (byte == 'x'){ // for now instead of "\r\n" i use the char 'x'
printf( "Your message: %s", bytes);
bytes = NULL; // or {0}?
}
}

最佳答案

您应该将bytes定义为大小为最大消息长度的数组,而不是指针。

unsigned char byte, i;
unsigned char arr[10]; // 10 for example
i=0;
while (true){
byte = get();
arr[i] = byte;
i++;
if (byte == 'x'){
printf( "Your message: %s", arr);
}
}

当您将bytes定义为指针时,它不指向任何内容,并且写入它可能会删除程序中的其他数据,您可以使用使其成为数组或在运行时为其分配空间>malloc

关于c - 将字符存储在字符指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32435012/

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