我希望在内存中分配不同类型的变量.
目前,我有这样的代码:
//key=4bytes(char), name= 4chars=4bytes, age=4bytes ==>12* 20 elements
uint16_t * table = (uint16_t*)malloc(12*20);
char* key = (char*) table ;
char* name = (char*) table ;
int* age = (int*)table ;
key[0] = 'c';
key[1] = 'i';
key[2] = 'r';
// key = "cir";
// name = "pav";
name[0] = 'p';
name[1] = 'a';
name[2] = 'v';
*age = 15;
char* key2 = (char*) table ;
char* name2 = (char*) table ;
int* age2 = (int*)table ;
// key2 = "ric";
// name2 = "vap";
key2[0] = 'r';
key2[1] = 'i';
key2[2] = 'c';
name2[0] = 'v';
name2[1] = 'a';
name2[2] = 'p';
*age2 = 12;
我现在想要访问(Print Tf To Screen)内存中的不同变量,但我不能这样做,除非是在上面代码末尾的print tf时的最后一个元素:
printf("%d ", *(table)); // prints 12
我try 用%s或%c执行*(table-4)
,但如果%c,则nothings works始终显示空白空间
如果我想通过*(table-12)
求出15,则为0
如何访问表without using struct中的不同值. 我看到了这个问题中的声明:How to store different types to allocated memory in C?
我想要的是: