gpt4 book ai didi

c - 如何在 C 中构造并返回字符串?

转载 作者:行者123 更新时间:2023-11-30 14:53:47 25 4
gpt4 key购买 nike

我正在尝试用 C 构造并返回一个字符串,但遇到了 function returns address of local variable [-Wreturn-local-addr]编译器警告。我得到了返回packet就像我想做的那样是行不通的,因为数据包是指向大小为 packet_size 的字符开头的指针,并且该内存地址在我的函数之外无效。我在 AVR 芯片上运行,不想使用 malloc 。我应该如何解决这个问题?

#include <stdio.h>
#include <string.h>
#include <stdint.h>

const char* construct_packet(const char* data);
void append(char* str, char c);

int main()
{
const char* my_packet = construct_packet("QERT");
printf("%s", my_packet);

return 0;
}

const char* construct_packet(const char* data)
{
const char training_chars[] = "___";
const char start_char = '>';
uint8_t checksum = 0;
for(uint16_t i = 0; i < strlen(data); i++) {
checksum += data[i];
}
const char checksum_char = checksum;

uint8_t packet_size = strlen(training_chars) + strlen(data) + 2; // Plus 2 for start byte and checksum byte
char packet[packet_size];

strcat(packet, training_chars);
append(packet, start_char);
strcat(packet, data);
append(packet, checksum_char);

return packet;
}

void append(char* str, char c)
{
str[strlen(str) + 1] = c;
}

最佳答案

如果您不想使用动态内存分配,也不想使用静态缓冲区,那么您可以尝试在堆栈上计算并提供内存缓冲区:

#include <stdio.h>
#include <string.h>
#include <stdint.h>

const char* construct_packet(const char* data, const char* training_chars, const char start_char, char* packet);
void append(char* str, char c);

int main()
{
const char data[] = "QERT";
const char training_chars[] = "___";
const char start_char = '>';
const uint8_t packet_size = strlen(training_chars) + strlen(data) + 2; // Plus 2 for start byte and checksum byte
char packet[packet_size];

const char* my_packet = construct_packet(data, training_chars, start_char, packet);
printf("%s", my_packet); // same as printf("%s", packet);

return 0;
}

const char* construct_packet(const char* data, const char* training_chars, const char start_char, char* packet)
{
uint8_t checksum = 0;
for(uint16_t i = 0; i < strlen(data); i++) {
checksum += data[i];
}
const char checksum_char = checksum;

strcat(packet, training_chars);
append(packet, start_char);
strcat(packet, data);
append(packet, checksum_char);

return packet;
}

void append(char* str, char c)
{
str[strlen(str) + 1] = c;
}

关于c - 如何在 C 中构造并返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47026824/

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