Comparison of string characters in C

Asked

Viewed 141 times

3

I’m trying to do an exercise that tests if there’s any white space before a string and remove if you have, but is returning the following error:

Segmentation failure (recorded core image)

I can’t understand why.

Code:

#include <stdio.h>
void removerEspacosEsquerda(char string[]) {
    int i, j, cont;
    char *string2, a;
    i = 0;
    cont = 0;
    while(string[i] != 0) {
        if(string[i] == ' ') {
            cont++;
        }
        i++;
    }
    i = 0;
    j = 0;
    printf("%d", cont);
    while(string[i] != 0) {
        if(i >= cont) {
            string2[j] = string[i];
        }
        i++;
        j++;
    }
    string = string2;
}
int main() {
    char *string;
    string = " teste";
    removerEspacosEsquerda(string);
    printf("%s", string);
}
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

2

Your code is too complex and the error occurred because of this, when we simplified it the error does not even have opportunity to appear. Do not need to have 2 loops (3 for the solution of the other answer) and need not have memory allocation:

#include <stdio.h>

void removerEspacosEsquerda(char string[]) {
    int cont = 0;
    for (int i = 0; string[i] != '\0'; i++, cont++) {
        if (string[i] == ' ') cont--;
        else string[cont] = string[i];
    }
    string[cont] = '\0';
}

int main() {
    char string[] = " teste";
    removerEspacosEsquerda(string);
    printf("%s", string);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

1

Segmentation failure occurs because the "string2" pointer has not been initialized.

#include <stdio.h>
#include <stdlib.h> // para malloc e free

void removerEspacosEsquerda(char string[])
{
  int i, j, cont;
  char *string2 = malloc(strlen(string)+1), a; // <-------------
  i = 0;
  ....
  ....
  strcpy(string, string2);
  free(string2); // <-------------
} // fim removerEspacosEsquerda

Note that I haven’t analyzed whether your space removal logic is correct, I’m just solving the problem of segmentation failure.

Browser other questions tagged

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