问题描述
我必须存储如下所示的数据->
我希望像set_data(data_id,index,data)
这样的界面将数据写入表中,而get_data(data_id,index)
则需要从表中读取数据
我必须用C代码来实现。
需要一些逻辑上的帮助来编写代码。
如何使用c中的结构来完成
想要实现这样的功能。
struct INDEX
{
U8 Len;
U8 data[];
};
struct DATA_ID
{
struct INDEX index[];
};
struct DATA_ID data_id[max];
data[]
的长度因每个索引而异,
index[]
的长度因每个data_id而异
解决方法
对于动态内存分配,您需要使用 malloc 。
一个提示:每次您要初始化长度(大小)未知的数据类型时,最好使用 malloc 。唯一的其他解决方案是,使用足够大的数据类型来初始化未知数据类型,但这只会浪费内存,而且通常还会浪费性能。
从https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm复制
#include <stdio.h>
#include <stdlib.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str,"tutorialspoint");
printf("String = %s,Address = %u\n",str,str);
/* Reallocating memory */
str = (char *) realloc(str,25);
strcat(str,".com");
printf("String = %s,str);
free(str);
return(0);
}
输出:
String = tutorialspoint,Address = 355090448
String = tutorialspoint.com,Address = 355090448