-2
int main (){

    char array[2] = {'hola', 'adios'};  
    int i = 0;

    while (i<3){
        printf("%c", array[i]);
        i++;
    }

    return 0;
}

I don't why the output is the final letter of each word, like this: as:)

And it appears a smiley face, wtf?

I simply want to output hola adios

frankie3
  • 89
  • 1
  • 1
  • 8

3 Answers3

4

You need strings, not chars. hola is a string, not a char. Strings are surrounded in "" not in ''. So you need

const char* array[2] = { "hola", "adios" };  

Now, this array has 2 elements, so loop through them

while (i<2){ /* also NOTE: 2 elements in the array */
    printf("%s", array[i]); /* note the "%s", it's not "%c" */
    i++;
}

I'd use for loop instead.

Why you don't have a compile-time error? See What do single quotes do in C++ when used on multiple characters? - it's similar in C.

Community
  • 1
  • 1
Kiril Kirov
  • 36,509
  • 22
  • 109
  • 183
2

You're creating array of 2 single char elements. Declare array of two strings, and use double-quotes to declare strings, and not chars:

char* array[2] = {"hola", "adios"}; 

Also, in printf, use %s for printing out strings. And i should be in range {0, 1} - don't include 2.

Nemanja Boric
  • 21,057
  • 6
  • 63
  • 89
1
char array[2] = {'hola', 'adios'};  

This is not valid. You are in the Undefined Behavior zone.

You need a char** or char[] [] and use "" instead of '' for your strings.

Arnaud Denoyelle
  • 28,245
  • 14
  • 82
  • 137
  • What's undefined here? See http://stackoverflow.com/questions/7459939/what-do-single-quotes-do-in-c-when-used-on-multiple-characters – Kiril Kirov Dec 20 '13 at 14:00
  • 1
    @KirilKirov Character literals are valid in C++. This question is about C. – Arnaud Denoyelle Dec 20 '13 at 14:01
  • Point taken, I've reverted my down-vote, as I'm not 100% sure it's valid in C. – Kiril Kirov Dec 20 '13 at 14:02
  • 1
    @ArnaudDenoyelle, From the C99 standard: *An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes*. Anyway, I think the implementation-defined value of the constant being converted to a `char` could potentially be UB that would most likely just wrap. – chris Dec 20 '13 at 14:05