another c pointer question

Posts: 195
Joined: 2009.02
Post: #1
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?
Quote this message in a reply
Posts: 1,488
Joined: 2002.09
Post: #2
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.

Scott Lembcke - Howling Moon Software
Author of Chipmunk Physics - A fast and simple rigid body physics library in C.
Quote this message in a reply
Posts: 195
Joined: 2009.02
Post: #3
Thanks, I always get so confused when dealing with c strings.
Quote this message in a reply
Posts: 869
Joined: 2003.01
Post: #4
You typically should to use strncpy() instead of strcpy() to prevent buffer overruns.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Pascal language (pointer) problem sealfin 3 6,491 Nov 27, 2012 04:38 AM
Last Post: sealfin
  Diferences between array and pointer initialized strings in C ferum 16 9,635 Jan 4, 2006 11:38 PM
Last Post: kelvin
  Member function pointer LongJumper 6 6,565 Oct 31, 2005 05:53 PM
Last Post: LongJumper
  Cocoa Method to C Pointer KiroNeem 11 8,921 Sep 12, 2005 10:08 AM
Last Post: Zekaric