Bharath R
Bharath R

Reputation: 19

Question about returning string in c language

#include<stdio.h>
char*display();

int main() {

    char*one=NULL;

    one=display();

    one[3]='9';

    printf("%s",one);//doubt(why we are not using the de reference operator)
}


char*display(){

    static char a[30]="hello";   

    return a; 

}

why we are not using the de reference operator(*) for displaying the value at the string ,instead we simply put the pointer variable pointing towards the string to print that string.

Upvotes: 1

Views: 74

Answers (1)

chux
chux

Reputation: 153498

why we are not using the de reference operator(*) for displaying the value at the string ... ?

The argument that matches the "%s" in printf("%s",one); is a pointer, a pointer to a string. A string is more like an array of characters than a pointer. Arrays cannot be received by a function, but a pointer to an array can be received.

printf("%s... expects a string pointer, reads the character pointed to by that pointer, prints the character, increments its copy of the pointer and repeats until a null character is read.

If code use *one, that would pass the value of the first character of the string and printf() would lack information about where the next characters in the string exist.


Notes:
char *display() returns a pointer, not a string. one, in main(), then points to a string.

An array is not a pointer.
A pointer is not an array.

Upvotes: 1

Related Questions