Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
Old Oct 4th, 2005, 4:11 PM   #1
tempest
Programming Guru
 
tempest's Avatar
 
Join Date: Oct 2004
Posts: 1,041
Rep Power: 5 tempest is on a distinguished road
Send a message via ICQ to tempest Send a message via AIM to tempest Send a message via Yahoo to tempest
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]
__________________

tempest is offline   Reply With Quote
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 12:54 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC