c - Storing and accessing different data types with unsigned short pointer
问题描述
I haven't done much work with pointers, so this whole thing is kinda new to me - forgive me if I'm missing something obvious. What I'm trying to do is save different types of variables into a uint16_t pointer. My pointer is like this:
uint16_t* ptr = (uint16_t*) malloc(6 * sizeof(uint16_t));
.
I could use a char or float pointer, but my goal is to understand how different types of variables could be saved into an integer pointer and then read back by manipulating the memory. I've saved a char variable like this: *(ptr) = ("X"); *(ptr + 1) = "P";
And a double variable like this : *(ptr + 2) = (float)M_PI;
.
When I try to print the value at *(ptr) as a char, I do get a char, but it is not X (I get T). Trying to print the float gives me 0.00000.
I haven't found any useful topics that cover this issue and would be very glad if someone could explain the storing and retrieving of this information to me. Thank you!
解决方案
When I try to print the value at *(ptr) as a char, I do get a char, but it is not X (I get T).
There are several problems in your code
*(ptr) = ("X"); *(ptr + 1) = "P";
Should be written as :
*(ptr) = 'X'; (no need for bracket)
*(ptr + 1) = 'S'; // also for 'S'
in C, " is used for strings and ' for single character
*(ptr + 2) = (float)M_PI;
You are trying to fit 4 bytes into a ptr that can contain only 2. (assuming float 32 bits on your OS)
- (uint16_t*) malloc(6 * sizeof(uint16_t));
Don't cast malloc (MikeCAT)
Find the way to achieve what you desire without facing undefined behaviors or cast issues by regrouping your variables into a structure:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct mystruct {
float f;
char c;
char b;
} t_mystruct;
void main ()
{
t_mystruct *ptr = malloc(sizeof(t_mystruct));
ptr->c = 'X';
ptr->b = 'S';
ptr->f = (float)M_PI;
printf("%c %c %f\n", ptr->c, ptr->b, ptr->f);
}
compile with gcc test.c -lm && ./a.out
推荐阅读
- django - 如何自定义 Django ModelForm 字段?
- javascript - 准备就绪时带有 Promise 输出的 Javascript
- python - 测试 Flask-Wtform 日期时间字段
- ios - 使用 Expo 构建的 React-Native 应用程序在设备 (iOS) 上的模拟器上运行良好,引发 Expo,但在使用 TestFlight 运行时崩溃
- react-native - 来自 fatsecret.com 的 Axios React Native Token 请求
- python - 在 Django 中使用服务器启动从执行中排除 python 文件
- python - 获取熊猫数据框中多个选定列的平均值
- git - 如何创建一个从原始版本继承更新的复制 git 存储库
- matlab - 在矩阵行中创建三叉树场景
- dependency-injection - 解析单例泛型,其中 T 是实现接口的控制器