Error accessing string array

Asked

Viewed 176 times

1

I have the following code:

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

int main() {
    char v[]= {'Brasil', 'Alemanha', Japão'};

    int i = 0;
    for (i=0; i<4; i++){
    printf("%s", v[i]);
    }
}

However, when I compile opens the terminal and the message appears:

countries.exe has stopped working

Erro

What is wrong?

1 answer

5


The code has several errors.

Strings should be delimited by double and not simple quotes which are reserved only to delimit a character.

Is creating a array of strings, but is declaring a array of characters. With the modification I made is creating a array pointer char which is exactly what produces a string. In case the compiler will allocate the three strings in a static area and will put a pointer to these strings in the array.

The loop is reading one more item than exists, if there are 3, it has to go up to 2, since the first starts at 0.

#include <stdio.h>

int main(void) {
    char *v[] = { "Brasil", "Alemanha", "Japão" };
    for (int i = 0; i < 3; i++) printf("%s\n", v[i]);
}

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

  • Thanks friend. It worked :) I kept your reply. Very complete

  • 2

    @Guilhermeduarte Hello Guilherme! Mark the answer as accepted by clicking on the check mark on the left side of the text, Please! :)

Browser other questions tagged

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