|
Setting value to char pointer element....
It seems like this shoud be very basic, what i'm trying to do is this...
if i have str:
char *str = "Hello, world!";
and i want to change the first H to an h for example, how could that be done?
I've come up with this solution after lots of frustration, but it seems like there should be an easier way to accomplish this.
I have tried memset, etc, always gives a seg fault...
[php]
/*
Output:
*ello, world!
H*llo, world!
He*lo, world!
Hel*o, world!
Hell*, world!
Hello* world!
Hello,*world!
Hello, *orld!
Hello, w*rld!
Hello, wo*ld!
Hello, wor*d!
Hello, worl*!
Hello, world*
*/
#include <stdio.h>
#include <stdlib.h>
char *strchr_rep(char *buf, char ch, int pos) {
int i;
char tmp[2] = " ",
*nbuf = (char *)malloc(strlen(buf));
if(pos >= strlen(buf) || pos < 0)
return NULL;
for(i=0;i<pos;i++) {
tmp[0] = buf[i];
strcat(nbuf, tmp);
}
tmp[0] = ch;
if(pos == 0)
strcpy(nbuf, tmp);
else
strcat(nbuf, tmp);
for(i=pos+1;i<strlen(buf);i++) {
tmp[0] = buf[i];
strcat(nbuf, tmp);
}
return nbuf;
}
int main(int argc, char* argv) {
char *str = "Hello, world!", i;
for(i=0;i<strlen(str);i++)
printf("%s\n", strchr_rep(str, '*', i));
return EXIT_SUCCESS;
}
[/php]
__________________
|