Hey guys, so I'm trying to write a little program that will put together any number of strings passed to it into a single string and then print out that string backwards.
I think I have everything correct but I keep getting a "Segmentation fault (core dumped)" error after compiling and running. So far the output I get looks like this if I enter "Hello" and "World" for my two strings:
argc = 3
argv[1] = Hello
argv[2] = World
len = 12
string = ÿ9
string = ÿ9Hello World
Segmentation fault (core dumped)
Also, how can I fix that I'm getting that weird ÿ9 character for my *string[0] index? I'd like my string "Hello World" to start from *string[0].
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse(char *string);
/******************************************************************************
* main() function
******************************************************************************/
int main(int argc, char **argv){
//check for arguments
if ( argc < 2 )
{
printf("Usage : reverse <string>\n");
return 0;
}
printf("argc = %d\n", argc);
//concatenate the strings
int i = 1;
int len = 0;
while ( i < argc )
{
printf("argv[%d] = %s\n", i, argv[i]);
i++;
}
i = 1;
while ( i < argc )
{
len += strlen(argv[i]) + 1;
i++;
}
printf("len = %d\n", len);
char *string[len];
i = 1;
printf("string = %s\n", *string);
while ( i < argc )
{
strcat(*string, argv[i]);
strcat(*string, " ");
i++;
}
//reverse the string
reverse(*string);
printf("string = %s\n", *string);
return 0;
}
/******************************************************************************
* reverse() function using recursion
******************************************************************************/
void reverse(char *string)
{
if(*string != '\0')
{
reverse(string+1);
}
printf("Reverse of String = %s\n", *string);
}