OutOfReach
December 21st, 2008, 10:22 PM
I have this code from an exercise I was doing from my book:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/* A small exercise from Chapter 10 of Programming in C. */
// Prototypes
void insertString(char string[], int index, char insertString[]);
int main(void)
{
char text[] = {"the wrong son"};
char text2[] = {"per"};
printf("%s\n", text);
printf("%s\n", text2);
insertString(text, 10, text2);
printf("The new string is: %s\n", text);
return 0;
}
void insertString(char string[], int index, char insertString[])
{
int length = strlen(string);
int inLength = strlen(insertString);
int i, j;
char tmpString[length];
strcpy(tmpString, string);
for (i=0, j=index; i < inLength; i++, j++)
{
string[j] = insertString[i];
}
for (i=index; j < (length+inLength); i++, j++)
{
string[j] = tmpString[i];
}
string[j] = '\0'; /* Finish it off with the string terminator */
}
Yes, the insertString() function might not be the best but it works and I'm still pretty new to all this.
Anyways, when I compile in Code::Blocks I get the following warnings:
warning: deprecated conversion from string constant to ‘char*’
warning: deprecated conversion from string constant to ‘char*’
On the line of:
insertString(text, 10, text2); in the main() function.
When I compile by command line I get no warnings, odd. When I run the program, well, here's the output:
the wrong son
per
The new string is: the wrong person
Segmentation fault
Any help? I'm really stumped on this one.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/* A small exercise from Chapter 10 of Programming in C. */
// Prototypes
void insertString(char string[], int index, char insertString[]);
int main(void)
{
char text[] = {"the wrong son"};
char text2[] = {"per"};
printf("%s\n", text);
printf("%s\n", text2);
insertString(text, 10, text2);
printf("The new string is: %s\n", text);
return 0;
}
void insertString(char string[], int index, char insertString[])
{
int length = strlen(string);
int inLength = strlen(insertString);
int i, j;
char tmpString[length];
strcpy(tmpString, string);
for (i=0, j=index; i < inLength; i++, j++)
{
string[j] = insertString[i];
}
for (i=index; j < (length+inLength); i++, j++)
{
string[j] = tmpString[i];
}
string[j] = '\0'; /* Finish it off with the string terminator */
}
Yes, the insertString() function might not be the best but it works and I'm still pretty new to all this.
Anyways, when I compile in Code::Blocks I get the following warnings:
warning: deprecated conversion from string constant to ‘char*’
warning: deprecated conversion from string constant to ‘char*’
On the line of:
insertString(text, 10, text2); in the main() function.
When I compile by command line I get no warnings, odd. When I run the program, well, here's the output:
the wrong son
per
The new string is: the wrong person
Segmentation fault
Any help? I'm really stumped on this one.