Home > front end >  Why we didn't use * during dereferencing the pointer?
Why we didn't use * during dereferencing the pointer?

Time:02-23

In the below code, we get a pointer from strdup(source) and we store it in a pointer named target. Now, when we print the string using pointer, we don't add * at the beginning of the pointer: why is it so? As I studied whenever we want to dereference any pointer we use *pointer_name. If we add * in the below code, we get an error. I am very beginner, so pls ans in easy words.

#include<stdio.h>
#include<string.h>
 
int main()
{
    char source[] = "Programming";
 
    char* target = strdup(source);
 
    printf("%s\n",target);
    return 0;
}

CodePudding user response:

printf expects a char pointer in the place of the %s specifier.

https://en.cppreference.com/w/c/io/fprintf

CodePudding user response:

strdup() returns a char*, hence the char* type of target. target holds a pointer to the first character in an array of chars. printf("%s", string) expects string to be a char*, so there’s no reason to do anything to target; just pass it to printf().

If you dereferenced target, you would get a single char (P in this case). printf() would then complain that you had supplied a character instead of a string (pointer to character). Even worse, the program could compile, and then printf() would try to print the string at address P (0x50), which would result in probably unwanted behaviour.

When working with arrays—a string is a type of array—you rarely want to dereference the array.

CodePudding user response:

char* target = strdup(source);
printf("%s\n",target);

Why we don't use *target in the code above?

The explanation is quite simple, as already stated in previous answers: target has type char pointer, which is exactly what printf() wants in the above call.

Now, printf() is a little complicated because its semantic is not simple - basically it accepts zero or more arguments after the first, of any type. But if we use strdup() again, maybe it is simpler:

char* target2 = strdup(target);

Here, if you wrote strdup(*target), the compiler might warn that you are passing a char instead of a pointer to char.

  • Related