iDevGames Forums
another c pointer question - Printable Version

+- iDevGames Forums (
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Programming Languages & Scripting (/forum-8.html)
+--- Thread: another c pointer question (/thread-219.html)

another c pointer question - NelsonMandella - Mar 25, 2010 12:45 PM

char *c = malloc(255);
if (c != NULL)
        strcpy(c, "Hello world!");

void *ptr = c;

char *c2 = ptr;

It appears to work, but is it safe? Does the void pointer throw out information pertaining to the number of elements pointed to, or does it simply overlook it, thus allowing c2 access to it(the number of elements) once again?

another c pointer question - Skorche - Mar 25, 2010 01:38 PM

Pointers don't know anything about sizes of the things that they point to. That's why you can put a pointer into the middle of an array if you want.

What's really happening here is that C strings are null terminated strings. This means that the string "the" is actually 4 characters long. -> 't', 'h', 'e' followed by a zero. To find the length of a string, you actually have to check each character until you find a zero in it.

another c pointer question - NelsonMandella - Mar 25, 2010 02:51 PM

Thanks, I always get so confused when dealing with c strings.

another c pointer question - DoG - Mar 26, 2010 03:49 AM

You typically should to use strncpy() instead of strcpy() to prevent buffer overruns.