The code doesn't work because %s
accepts the pointer to the string, but an integer is passed. printf()
may think that the integer is the pointer, but actually there are almost no chance that the integer becomes a valid pointer.
printf("%s",*p);
invokes undefined behavior because char
is passed where char*
is expected. You should remove *
here. Also p
should be const char*
instead of char*
to tell the compiler that the string is not modified.
void fun(const char *p)
{
printf("%s",p);
}
To pass strings (sequences of characters terminated by a null-character) without passing its address, you can put strings in structures and pass them.
#include <stdio.h>
struct str_container {
char str[32];
};
void fun(struct str_container sc)
{
printf("%s",sc.str);
}
int main(void)
{
struct str_container str = {"hello"};
fun(str);
return 0;
}