我希望在内存中分配不同类型的变量.

目前,我有这样的代码:

    //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?

我想要的是:

enter image description here

推荐答案

您希望您的代码模拟用于学习目的的 struct array.您的代码不起作用,因为您在同一地址写入了不同的fields.您应该对不同的fields使用不同的偏移量,并对连续的条目使用不同的偏移量.我建议您编写帮助器函数来一次初始化structured个元素:

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

// copy a string with truncation
void pstrcpy(char *dest, size_t size, const char *src) {
    if (size) {
        while (*src && size-- > 1) {
            *dest++ = *src++;
        }
        *dest = '\0';
    }
}

void set_entry(char *e, const char *key, const char *name, int32_t age) {
    pstrcpy(e + 0, 4, key);
    pstrcpy(e + 4, 4, name);
    int32_t *p = (int32_t *)(e + 8);
    *p = age;
}

void print_entry(const char *e) {
    const char *key = e;
    const char *name = e + 4;
    const int32_t *age = (const int32_t *)(e + 8);
    printf("%s,%s,%ld\n", key, name, (long)*age);
}

int main() {
    char *table = malloc(12 * 20);
    if (table == NULL)
        return 1;

    set_entry(table + 0 * 12, "cir", "pav", 15);
    set_entry(table + 1 * 12, "ric", "vap", 12);
    // ...

    print_entry(table + 0 * 12);
    print_entry(table + 1 * 12);

    free(table);
    return 0;
}

C++相关问答推荐

与unions 的未定义行为

在C中使用强制转换将uint16_t转换为uint8_t [2]是否有效?

从内联程序集调用Rust函数和调用约定

单指针和空参数列表之间的函数指针兼容性

为什么GDB/MI进程的FIFO循环中有read()阻塞

如何将字符**传递给需要常量字符指针的常量数组的函数

将 struct 传递给函数

CC2538裸机项目编译但不起作用

指向不同类型的指针是否与公共初始序列规则匹配?

变量的作用域是否在C中的循环未定义行为或实现定义行为的参数中初始化?

使用nmake for程序比Hello World稍微复杂一些

如何使用FSeek和文件流指针在C中查找文件的前一个元素和前一个减go 一个元素

初始成员、公共初始序列、匿名联合和严格别名如何在C中交互?

C语言中奇怪的输出打印数组

通过对一个大的Malloc内存进行切片来使用Malloc的内存片

即使我在C++中空闲,也肯定会丢失内存

问题:C#Define上的初始值设定项元素不是常量

无算术运算符和循环的二进制乘法

存储和访问指向 struct 的指针数组

(GNU+Linux) 多个线程同时调用malloc()