I just started teaching myself c with a book called practical c programming, and i can't figure out one of the exercises. I'm supposed to write a function that scans a character array for the character - and replace it with _. I tried doing it, but i don't think i fully understand how to pass arrays between functions or whatever. Here's what i got, please help me.

char replace(char string[100])
{
 int i; //increment
 
 for (i=0; string != '\0'; i++)
  {
   if (string[i] == '-')
     string[i] = '_';
 }
 return(string[i]);
}

int main()
{
 char line[100];

 printf("Enter a string: ");
 fgets(line, sizeof(line), stdin);

 printf("New string: %s", replace(line));
}

Recommended Answers

All 8 Replies

> string != '\0'
Compare with string != '\0'

Also, make the function return a char*, and return string.
That is, if you want to print the result with %s

i tested it and it just said memory fault

Tested what?
If you made changes, and it doesn't work, then post your updated code.

char replace(char string[100])
{
 int i; //increment

 for (i=0; string[i] != '\0'; i++)
  {
   if (string[i] == '-')
     string[i] = '_';
 }
 return(*string);
}

int main()
{
 char line[100];

 printf("Enter a string: ");
 fgets(line, sizeof(line), stdin);

 printf("New string: %s", replace(line));
}

thank you :)

char *replace(char string[100])

And now something extra. You don't need to care how long the string passed as an argument is.
You can write it like char *replace ( char string[] ) or even like char *replace( char *string ).

Well i haven't gotten to pointers yet, i started reading about it in the first book i tried, but they're more towards the end of this one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.