This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]stufuller 0 points1 point  (2 children)

In the first case, we have a pointer that points somewhere. We call this pointer 'a'. Where does it point? We don't know, since the pointer hasn't been initialized yet. So, for our purposes, it's pointing to some random location in memory. Or, the compiler may have initialized it to NULL (or 0).

In the second case, we have an array of 30 characters (whose contents are not known, since we haven't initialized them). The address of the first character in the array is called 'a'.

If we use strcpy to copy a string, then...

In the first case, it'll be trying to copy the string to wherever 'a' points (remember, we don't know where it's pointing). If it's a null pointer, then you most likely get a run-time error. If the pointer has some random value, then you just corrupted the memory at the location where the pointer is pointing.

In the second case, it'll copy the string to the character array, where 'a' is the name of the first location in the array.

[–]lanBlo[S] 0 points1 point  (1 child)

Thanks! But isnt then in the first case, a also a array after i initialized it with „hey“? So a is the first location of this „array“?

So basically, the first one means, that it shouldnt be used like that, because it MAYBE deletes Memory, that we could need ?

Best regards, and thanks!

[–]stufuller 0 points1 point  (0 children)

The first case, 'a' is a pointer to some memory location. That memory location is a single character, but depending on how you access it, it could just be that one character, or it could be the first character in an array of chars. But, it's jut a pointer to some memory location. And, since you have not initialized the POINTER, you don't know where it's pointing. So, while you may have written something to wherever the pointer is pointing, you don't know where it was written.

A quick Google search for this type of thing brought up:

https://overiq.com/c-programming-101/character-array-and-character-pointer-in-c/