简体   繁体   中英

why printf doesn't accept a pointer as an argument

why codeblocks crashes when I try to run this code :

#include <stdio.h>
#include <stdlib.h>

void main(void)
{
    char *ch= "Sam smith";
    printf("%s\n",*ch);
}

but it works fine when I remove *ch in printf and replace it with just ch like this

void main(void)
{
    char *ch= "Sam smith";
    printf("%s\n",ch);
}

shouldn't *ch mean the content of the address pointed to by ch which is the string itself, and ch mean the adress of the first element in the string? so i expected the opposite!

I use Code blocks 17.12, gcc version 5.1.0, on windows 8.1 .

*ch dereferences the pointer to yield the data it points to. Here the first character of the string.

Providing the wrong specifier to printf is undefined behaviour (passing a value where printf expects a pointer)

printf("%c\n",*c);

would print the first character, without crashing. If you want to print all the string using %c (or use putchar ), loop on the characters. But that's what %s does.

As a side note, better use const to reference literal strings so no risk to attempt to modify them:

const char *ch= "Sam smith";

why codeblocks crashes when I try to run this code :

 char *ch= "Sam smith"; printf("%s\\n",*ch);

ch is of type char * .

The %s conversion specifier expects a char * .

You pass *ch , which is the dereferenced ch , ie of type char .

If conversion specifiers do not match the types of the arguments, bad things (undefined behavior) happens.

shouldn't *ch mean the content of the address pointed to by ch which is the string itself

There is no data type "string" in C, and thus no "pointer to string".

A "string", in C parlance, is an array of characters, or a pointer to an array of characters, with a null-byte terminator.

ch is a char * , a pointer to the first character of that array - a string, so to speak.

*ch is a char , the first character of that array.

In C, You do not dereference a pointer to a string, when you want to use the whole string the pointer points to. This dereferencing process would result in the first character of the respective string, which is not what you want.

Furthermore, it is undefined behavior if a conversion specifier does not match to the type of the relative argument.


Thus,

printf("%s\n",*ch);

is wrong. *ch is the first character in the string, in this case S , of type char but the %s conversion specifier expects an argument of type *char .

printf("%s\n",ch);

is correct. ch is of type *char as required by the conversion specifier %s .

So, Codeblocks " crashes " apparently because of the mismatching argument type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM