Error to replace characters

Asked

Viewed 38 times

0

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

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

It even detects the letters and makes a switch. But instead of putting '*' it puts the following character: inserir a descrição da imagem aqui

1 answer

2


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

Just switch your insertion line to:

        mensagem[i] = '*';

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

By coincidence, I wrote a lot about this functioning of C strings in another response these days - worth taking a look there: How to turn a character into an integer in C?

  • Perfect! Thanks for the solution and the great explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.