【发布时间】:2019-06-23 18:29:54
【问题描述】:
我试图在结构内的另一个指针内分配一个字符指针。我的环境没有 malloc/calloc,因此动态内存分配不是一种选择。我如何才能在 read_string_from_byte_array() 函数中填充字符指针?
typedef struct custom_string
{
char textt[5];
int length;
}custom_string;
typedef struct custom_string_container
{
custom_string* string;
}custom_string_container;
void read_string_from_byte_array(custom_string_container* string_container)
{
char* byte_array = "12345";
int i;
puts("assigning");
for(i = 0; i < 5; i++)
{
string_container->string->textt[i] = byte_array[i]; //failing with exit code 139
}
puts("done assigning");
}
void main()
{
//dynamic memory allocation is strictly prohibited
custom_string_container string_container;
read_string_from_byte_array(&string_container);
printf("read string is %s \n", string_container.string->textt);
}
【问题讨论】:
-
你得到什么警告?
-
您显示的代码存在多个问题。首先,您使用没有初始化的指针(
string_container->string没有初始化为指向任何地方)。其次,您的textt成员是一个指向char的指针 数组,即它可以被视为一个(可能的)字符串数组。第三,您忘记了 C 中的char字符串实际上称为 null-terminated 字节字符串。 null-terminator 是所有标准字符串函数用来查找字符串结尾的函数(包括带有"%s"格式说明符的printf函数)。 -
您的
char* textt[5]字段是由五个字符指针组成的表,因此ttext[i]是char*和byte_array[i]是char并且您正在尝试将char分配给char*。 -
char* textt[5] 是一个错字。
-
minimal reproducible example 的一点是我们基本上应该能够复制粘贴它并获得与您获得的完全相同的结果。这包括获得与您可能遇到的完全相同的构建警告和错误,如果您没有收到任何构建警告或错误,请确保您显示的代码也没有任何警告或错误,即使从编译器启用更多警告也是如此。
标签: c memory-management dynamic-memory-allocation