What i am trying to accomplish here is taking an cString and replacing a certain character with another which place i find via using the strchr() function.
what i can’t figure out is how you can replace the character all my attempts (below commented out) all produce either an unedited string or crash the program. i believe i am going in the right direction with replacing the character (take the starting address of char *c and add n (the number of bytes forward the character i want to replace is) and then write to that new address.), but i can’t seem to get it to function correctly.
any help is appreciated.
int main()
{
char *c, *sch;
int n;
c = "this is a test\n";
sch = strchr(c, 'a');
if(sch != NULL)
{
n = sch-c+1;
printf("%d\n", (int)sch);
printf("%d\n\n", (int)c);
printf("'a' found at: %d", n);
}
/////////////////////
//sch = &c;
//*(sch + n) = 'z';
/////////////////////
//*(c + n) = 'z';
/////////////////////
//c[n] = 'z';
/////////////////////
printf("\n\n%s", c);
getchar();
return 0;
}
Edit: first of all,
cshould be an array and not a pointer to a string literal, since string literals are stored in read-only memory, and trying to modify them will usually result in a crash.So, first of all,
This initializes a modifiable string to that value, that you can edit without problems.
In general, you shouldn’t directly assign string literals to
char *, because you can incur in this kind of problems; instead, assign them only toconst char *, that way any modification attempt will result in a compilation error.Then,
strchralready returns a pointer to the matching character (as stated in the documentation), you can simply change it directly, no pointer arithmetic is involved:Still, if you want to experiment with pointer arithmetic, there’s an error in the definition for
n:If then you use it as an index of the string, you should remove that 1, because arrays (and strings) are zero-based. In other words: if you assign to
nthat value, the following code:(which is equivalent to
)
Will mean
that is,
i.e. the character following the one found by
strchr. Removing the+1will do the trick (although it’s just a convoluted way to simply say*sch='z').The other try is wrong because in your code
&cwill yield achar **, i.e. a pointer to a pointer to char, which is not what you want.