-
Why won't this run?
I don't have any errors but when it runs it tells me the program is an illegal operation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void insert(char *str, char *substr, int i){
char buffer[255];
int x;
/* copy everything from index to end of str into buffer */
for(x=0;x<strlen(str)-i; x++){
buffer[x] = str[x+i];
}
/* cut off everything from index to end of str */
str[i] ='\0';
/* hook together str + substr + buffer */
strcat(str,substr);
strcat(str,buffer);
}
int main(int argc, char *argv[])
{
char str[255]= "helloworld";
char substr[25]= "wide";
int i = 5;
insert(str,substr,i);
printf(str);
return 0;
}
-
In insert() change
str[i] ='\0';
to
buffer[i] ='\0';
-
buffer and str both need to be null terminated after you cut str up into fragments in order to be used in strcat. Your code puts the null terminator at end of first fragment, str[i], but I think it cuts off the null terminator at end of original str before it can be put into buffer[]. If I'm correct (haven't worked out the details myself) then changing < to <= in terminating condition of for loop may be easiest way to change this.