While compiling and executing the below program i am getting a warning during compilation and seg fault during execution.
Warning
program.c: In function main:
program.c:17: warning: passing argument 2 of convertString from incompatible pointer type
line 17 is the call to convertString(input, &output);
attaching the debugger is can see the segfault is occuring at the below line
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400521 in convertString (input=0x7fffffffd100 "abcdefg", output=0x7fffffffd0f0) at program.c:9
9 **output = *input;
(gdb) s
#include<stdio.h>
#include<string.h>
void convertString(char *input, char **output)
{
if(strlen(input)== 0)
{
return;
}
**output = *input;
(*output)++;
convertString(input+1,output);
}
int main()
{
char input[] = "abcdefg";
char output[sizeof(input)];
convertString(input, &output);
printf("%s", output);
return 0;
}
Please help me where i am doing wrong.
The problem is that output
is not a pointer, it's an array, and using the address-of operator on an array gives you a (single) pointer to the array (in your case of type char (*)[8]
). For clarification: (void *) output == (void *) &output
, both the decayed pointer of the array, and the pointer to the array, are equal.
So you're not really passing a pointer to a pointer to char
to the function.
Besides the above, I see no reason that the function should take a pointer to a pointer, a plain single pointer should be enough. Otherwise you will get wrong result when using output
in the printf
call as then output
would point beyond the end of the string.
Also, you don't terminate the output
string.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments