Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Why isn't this c code working?

include<stdio.h>

#include<stdlib.h>

// replace character 'search' with 'replace' in array "text"

char * char_replace(char * text, char * search, char * replace)

{

// ans_p will point to the beginning of the "text" character array

char * ans_p = text;

// iterate through every character within "text"

// stop when "text" is pointing to a null character

while(*text != '\0')

{

// if the two characters are equal ...

if (*(ans_p) == *(search))

{

// replace the character

*(ans_p) = *(replace);

}

// increment the text pointer

*text++;

}

return ans_p;

// return the pointer to the beginning of the array

}

// main function

int main()

{

// the string to search within is text[]

// the character to look for is *search

// the character to replace *search with is *replace

char text[] = "This is part 2 of the lab", * search = "2", * replace = "3";

// print statement before, should be "This is part 2 of the lab"

printf("before:\t%s\n", text);

// perform search and replace the 3 with a 2

char * new_string = char_replace(text,search,replace);

// print out the modified statement, "This is part 3 of the lab"

printf("after:\t%s\n", new_string);

return 0;

}

When I run it it outputs the same thing rather than changing it from 2 to 3.

1 Answer

Relevance
  • 1 decade ago

    Because you never ever move ans_p forward! You doing text++ instead of ans_p++ and you checking if (*text == '\0') instead of (*ans_p == '\0').

Still have questions? Get your answers by asking now.