I have a question about language!

Asked 2 years ago, Updated 2 years ago, 27 views

An attempt was made to remove blank characters within the str string defined in the main function and output them. Through the erase_blanks function. At this time, the temp variable is defined in the erase_blanks function Successfully copied the string that removed the space. Then pass the address value of temp to str and exit this function Temp disappeared because it was a local variable, and the result came out spaced. How should I modify it? <

void erase_blanks(char* str) {
    char* temp = (char*)malloc(sizeof(char)*BUFFER_LENGTH);
    int i = 0;
    int j = 0;
    while (str[i] != '\0') {
        if (str[i++] != ' ') {
            temp[j++] = str[i - 1];
        }
    }
    temp[j] = '\0';
    str = temp;
}

int main(void) {
    char* str = "aef aefe e ";
    erase_blanks(str);
    printf("%s", str);
        return 0;
    }

c

2022-09-22 19:04

1 Answers

Use strcpy() in <string.h> to copy a string.
The function prototype is as follows:

#include <string.h>
char *strcpy(char *string1, const char *string2);

A library function that copies string2 to string1, where string2 must contain null characters (\0).

Try changing it like this.

void erase_blanks(char* str) {
    char* temp = (char*)malloc(sizeof(char)*BUFFER_LENGTH);
    int i = 0;
    int j = 0;
    while (str[i] != '\0') {
        if (str[i++] != ' ') {
            temp[j++] = str[i - 1];
        }
    }
    temp[j] = '\0';
    strcpy(str, temp);
}

int main(void) {
    char str[BUFFER_LENGTH] = "aef aefe e ";
    erase_blanks(str);
    printf("%s", str);
        return 0;
}


2022-09-22 19:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.