-4

Suppose I have a string "hello". I want to pass it to a function

void fun(char *p)
{
printf("%s",*p);
}
int main()
{
fun("hello");
}

Example 2 :

How do I pass a character to char * ?

void fun(char *p)
{
printf("%s",*p);
}
int main()
{
char a = 'c';
fun(a);
}

Why is this not working?

How to pass a string to a function in c without passing its address

Aman Jain
  • 3
  • 3

1 Answers1

-1

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70