Error accessing string vector

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:

  

paises.exe stopped working

What's wrong?

    
asked by anonymous 30.10.2016 / 01:23

1 answer

5

The code has several errors.

Strings should be delimited by double and non-single quotation marks that are reserved only to delimit a character.

You are creating an array of strings , but you are declaring an array of characters. With the modification I've done, I'm creating an array from pointers to char which is exactly what produces a string . In case the compiler will allocate all three strings in a static area and will put a pointer to those strings in the array .

The loop is reading one more item than it exists, if there are 3, it has to go to 2, since the first one 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]);
    }
}

See running on ideone and on CodingGround .

    
30.10.2016 / 01:51