I'm quite new in programming with c++. But I have a question about pointers.
When do you have to write an asteriks and when not?
please, tell me if you know it.
Normal the asteriks refers to the contents of de memory space where the pointer refers to. but look at this example:
void Person::Setname(char *p)
{
strcpy(name, p);
}
I think that in the strcpy-function the pointer must have an asteriks because the strcpy function copies the contents. But why is it wrong when i write it with an asteriks??
C and C++ pointer and reference syntax can be rather confusing for beginners. This stems from giving the asterisk and ampersand similar but different meanings as modifiers for variable declarations and as operators. It is important to keep the two uses distinct in ones mind when reading and writing C++ code.
strcpy takes a pointer to the array as an input parameter so that it can loop until all characters are copied into the destination memory. If you used the * to dereference the pointer in the function call you'd be trying to pass a copy of the first character to the strcpy and it would be impossible for strcpy to know where the orginal memory buffer is. strcpy wants a pointer not an actual character and the compiler prevents you from passing a character. Within the function it must have the address of the array so that the entire string can be copied. Within the function, it might dereference the pointer as it loops and copies each char.
// this is just an example of how it could work. strcpy requires pointers
// as input params.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
strcpy(char* dest, constchar* src)
{
// dest / src are pointers to the memory
// use * to access the actual data at src/dest and perform copy
// also, immediately check if the result of the copy is NULL.
// once the NULL is copied, the loop stops and the function returns.
while((*dest = *src) != '\0')
{
// increment dest and src to get to the next character. This also could have
// been done within the while expression but i didn't want to convulute the
// the example too much.
dest++;
src++;
}
} // after returning, dest now points to new data