Follow

C programming question 

How cursed is it to treat a "char *" as a generic pointer? I'm running into a situation were I may need to do something like this:

char *x;
struct some_struct *data;
data = allocate_this_somehow();
x = (char *)data;

Other than not using in it places where a string is expected, should I be aware of anything? Does it trigger crazy weird UB? Does the char pointer type do weird things that I should be aware of? etc. etc.

· · Web · 4 · 1 · 2

re: C programming question 

@paul Before ANSI C, this was the preferred method. These days, the recommendation is to use void * for a generic pointer.

I'm not aware of any particular issues with using char * though.

C programming question 

@paul It's mostly safe in most cases; but why wouldn't you use void *?

C programming question 

@penguin42 I'm trying to hack in some functionality into this tiny TCL-like language to make it possible to throw C structs and data around, and I'd like to do so without modifying the original code.

C programming question 

@paul Oh it's probably fine then; there are some subtleties around systems which don't use byte addressing, but I can't remember what they are (and ~no one cares); but more importantly remember the char* says nothing about alignment, where as your structure might require alignment.

re: C programming question 

@penguin42 @paul On all systems that matter anymore, the userland can use unaligned data. It traps and causes a performance penalty, but it will not result in a SIGBUS. On Windows, this is even true in kernel. Of course it's better to keep it aligned.

Also, is this for just passing structs around, or is it for serialization/deserialization? If the latter, you have to byteswap into a defined order.

re: C programming question 

@pro
@penguin42 just passing structs around.

re: C programming question 

@paul It's perfectly fine. Just keep in mind, char is signed on some platforms, which is usually not what you want for bytes.
Also, representing structures through mismatching types via casting is undefined behaviour. So it's fine to do it for an opaque bytestream, but not fine for looking inside of structures. If you don't look, but just cast around, it's all fine though.

re: C programming question 

@paul The official way is to use unions, so if you really want to look inside structures in a standard-approved™ way, you should cast the bytes into a union, alongside what you'd like the layout you'd want to have. For some reason the standard's really pushing unions, even thought they're not that useful, and all compilers are fine with misrepresenting structures.

For byte arrays in FFmpeg we use uint8_t, which is quite a lot shorter to write than unsigned char.
Sign in to participate in the conversation
post.lurk.org

Welcome to post.lurk.org, an instance for discussions around cultural freedom, experimental, new media art, net and computational culture, and things like that.