Error in function to change characters

0

I have to create a function to make the exchange of some character. The exercise is this:
1. Build a function that receives a message, its size, and a and remove all occurrences of this character in the message putting * in its place. The function should return the total characters retired.

And I did the following:

#include <stdio.h>
#include <string.h>
#include <locale.h>
void filtro(char msg[500] ,int tamanho, char c){
    setlocale(LC_ALL,"portuguese");
    char mensagem[500];
    strcpy(mensagem,msg);
    int i,r=0;
    for (i=0; i<tamanho; i++){
        if(mensagem[i]==c){
            r++;
            mensagem[i] = "*";
        }
    }
    printf("\nMensagem modificada: \n %s", mensagem);
    printf("\nCaracteres retirados: %d", r);
}
void main(){
    setlocale(LC_ALL,"portuguese");
    char msg[500], c;
    printf("Escreva uma mensagem de até 500 caracteres\n");
    gets(msg);
    printf("Informe o caracter a ser removido: ");
    scanf("%c", &c);
    filtro(msg, strlen(msg), c);
}

But I get the following error message: [Warning] assignment makes integer from pointer without a cast

He even detects the letters and makes an exchange. But instead of putting the '*' it puts the following character:

    
asked by anonymous 20.08.2018 / 17:27

1 answer

2

In C, a string is fundamentally different from a single character. Strigns are just a memory address that contains a sequence of characters ending with a byte "0" - in the code above, just at the moment of inserting the new character, the "*", in the desired place, you use the string notation - double quotes - instead of the value of * , the compiler inserts into its string the lowest byte of the memory address of the string containing "*" ;

Just change your insertion line to:

        mensagem[i] = '*';

Instead of using double quotes - with this syntax, the ASCII code of the value in single quotes is used as a single byte that is inserted in that position.

Coincidentally, I've written extensively about how C strings work in another answer these days - it's worth taking a look there: How to transform a character into an integer in C?

    
20.08.2018 / 17:34