C passing string by reference to function
C passing string by reference to function
#include<stdio.h>
void fun1(int **iptr)
printf("%d ", **iptr); //shows value
void fun2(char **sptr)
//printf("%s", **sptr); shows segmentation fault
printf("%s", *sptr); //shows string
int main()
char *str = "Hi";
int *x, a = 10;
x = &a;
fun1(&x);
fun2(&str);
return 0;
Can anybody explain in short what's going on?
might be silly but i asked it anyway...
printf
%s
%d
Your two codes are not similar. Make a string variable, set a pointer to its address, use exactly as the pointer to int variable. Then compare behaviour.
– Yunnosch
Sep 7 '18 at 17:30
char **sptr ... printf("%s", **sptr); shows segmentation fault
--> A good compiler will warn of how this code is bad before you even need to run the code. Save yourself time and enable all compiler warnings. What warning do you get?– chux
Sep 7 '18 at 17:35
char **sptr ... printf("%s", **sptr); shows segmentation fault
thanks for help..im new to this..
– Sagar Gujarati
Sep 7 '18 at 17:54
1 Answer
1
When printing an integer, you pass the integer itself to printf
.
When printing a string of characters, you pass the address of the first character. In other words, you pass the pointer to the string.
printf
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Because
printf
is expecting a pointer as a parameter for the%s
specifier and a non-pointer for%d
– Eugene Sh.
Sep 7 '18 at 17:28