well the point isnt that it's unsafe to use pointers, just pointers that are unallocated. that means that when you declare something like:
char a[10];
the compiler will then set aside ten free bytes for this array. but if you declare something like:
char *a;
the compiler will only allocate a pointer, that is a variable that holds an address. that means that a points to some point in memory that the compiler decides to put it. this could be anywhere vital, which is the reason it is so unsafe. if the pointer points to code, data, whatever, the compiler is not picky, it will let you write to that address whenever you feel like. but if you use a function like malloc() to get a pointer to a portion of memory that is OK to write to there is no problem. also, pointers and arrays are sort of interchangeable, so you could write something like:
- Code: Select all
char a[10];
*a++ = 'Y';
and now a[1] contains the letter Y. However, i have found that freely mixing the two often leads me to problems and compiler errors so be careful and make sure you know what you are doing there. as for your question, malloc is never actually called unless you call it, so while this is correct:
char *hello = "Hello, world!";
this is not:
char *hello;
hello = "Hello, world!";
because in the first example the compiler will set aside the required space for the string and put it in the program at a certain point which it will then set the pointer value to. so if the compiler placed the string at address 0x1000, that is then where the pointer would be pointing to.
Sorry guys i like to ramble alot!!! I'll try to make it more short and sweet next time!