so I have this code, goal is to have a void *data
pointer, which is sometimes used to store a simple int
, sometimes a single char
array and sometimes I need to store an array of char arrays.
I'm making sure that I always know what type of data I have stored in the void pointer.
The code executes well in an online parser and this is the output of it:
sizeof 2 x char*: 8 str0: string1 addr: 2995278544 str1: bla2 addr: 2995278576 checking strings: str0: string1 addr: 2995278544 str1: bla2 addr: 2995278576
The plan was to malloc space for n char* pointers and save that pointer do void *data. Then change the type to "char **ptr" (pointer to a pointer), so I can save the addresses which strdup returns to that array and access them later. checkItems(uint8_t) does exactly that, it re-accesses the "void *data" pointer by changing it to "char **ptr" again to be able to access the memory addresses where the actual C strings are saved.
is this all correct? would one do this differently? should I use some kind of cast to the void *data pointer instead simply saying "char **ptr = data;"?
Thanks!
#include<stdio.h>
#include<stdint.h>
#include<string.h>
#include<stdlib.h>
#include<stdarg.h>
void copyItems(uint8_t num, ...);
void checkItems(uint8_t num);
void *data;
int main()
{
copyItems(2, "string1", "bla2");
checkItems(2);
}
void copyItems(uint8_t num, ...)
{
printf("sizeof %u x char*: %u\r\n", num, sizeof(char*), sizeof(char*)*num);
data = malloc(sizeof(char*)*num);
char **ptr = data;
va_list ap;
va_start(ap, num);
for (uint8_t n = 0; n < num; n++)
{
ptr[n] = strdup(va_arg(ap, char*));
printf("str%u: %s addr: %u\r\n", n, ptr[n], ptr[n]);
}
va_end(ap);
}
void checkItems(uint8_t num)
{
char **ptr = data;
printf("checking strings:\r\n");
for (uint8_t n = 0; n < num; n++)
{
printf("str%u: %s addr: %u\r\n", n, ptr[n], ptr[n]);
}
}