General problems in C

Asked

Viewed 104 times

-6

#include <stdio.h>
#include <string.h>

#define Nome "nome"
#define TAM_STRING 12

void main(void)
{
    char * str;

    str = (char*) malloc(TAM_STRING);

    if(str == NULL)
    {
        printf("Não já espaço para alocar");
    }
    else { (str,Nome);
    printf("Nome=[%s] tem [%d] caracters",str, strlen(Nome));
    int i = 0;
    for( i=0;i<strlen(Nome);i++)
    {
        printf("\nCaracter[%d] = [%c]\n", i , *(str+i));
        if(((*(str+i)=='a')|| (*(str+i)=='e'))|| (*(str+i)=='i')||(*(str+i)=='o')||(*(str+i)=='u')) printf("Vogal");
    }
}
free(str);
}
  • 4

    And what’s the mistake?

  • 3

    What should the code do? What is it doing?

  • 2

    *(str+i) is equal to str[i]. In my opinion the latest format is easier to read.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

5

The code has some errors:

#include <stdio.h>
#include <string.h>
#include <stdlib.h> // <=========== faltava este include
#define Nome "nome"
#define TAM_STRING 12

int main(void) { // <========== o retorno aqui precisa ser um int
    char * str = malloc(TAM_STRING); // <======= a declaração pode e deve ser mais simples
    if (str == NULL) printf("Não já espaço para alocar");
    else { 
        strcpy(str, Nome); // <======= acredito que queria usar esta função, não tinha o nome dela
        int tamanho = strlen(Nome);
        printf("Nome=[%s] tem [%d] caracters", str, tamanho);
        for (int i = 0; i < tamanho; i++) {
            printf("\nCaracter[%d] = [%c]\n", i , str[i]);
            if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') printf("Vogal");
        }
        free(str);
    }
}

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

Part of the problem is that the code was badly formatted, it is difficult to find errors like this. I would change a few more things, even considering that this is just something to test and that does nothing useful and with production quality. In fact I’ve changed some things.

Browser other questions tagged

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