首页 > 解决方案 > 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!

标签: cpointersmalloc

解决方案


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


推荐阅读