-1

How can we replace spaces in a string using pointers? I tried but unable to get it. While replacing space with hyphen, the control is coming out of the loop without tracing further.

while (*str != '\0')
{
    if (*str == ' ') 
    *str = '-'; 
    str++;
 }
 print(str);
Mike
  • 4,041
  • 6
  • 20
  • 37

2 Answers2

0

Pointers are special type of variables used to store address of other variables. when you changed value inside the str pointer with "str++", it then pointed to the next element and after the while loop str pointed to the last element of the string('\0'). So you must store the the address of the first character of the string to do something with it later.

int main() {
    char *s = "abcde", *str =s; // s,str stores address of first character

    while(*str!='\0'){
        if(*str ==' ') 
            *str='-';
        printf("%c", *str);
        str= str+1; // str now points to the next character. But s remains unchanged
    }


   }
priojeet priyom
  • 899
  • 9
  • 17
0

When you use pointers to do this and increment pointers then print(str) will show you end of str so \0.

You must store pointer to begin of str:

    char* str = (char*) malloc(sizeof(char) * 255);
    memcpy(str, "abc de", 255);
    char* beginStr = str;

    while(*str!='\0') {
        if (*str == ' ') {
            *str = '-';
        }
        str++;
    }

    printf("%s\n", beginStr);
    free(beginStr);
Igor Galczak
  • 142
  • 6