0

I want to print out all elements from the array to debug my program.

Here is the for loop to print out all elements of the array

for(int i = 0; i <= 9; i++) {
        printf("Words: %s\n", &words[i]);
    }

I have a header file that contains the const char array. This is required for a task. I know that its probably not good practice to put them in header files.

const char *words[10] = {'foo', 'bar', 'hello', 'world'};

My output when I run this code is very weird as it prints everything backwards.

Keywords: oof
Keywords: rab
Keywords: olleh
Keywords: dlrow

Sometimes, it would even add random full stops at the end of each keyword. Why is this? I have not written anything else but that.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
LtMuffin
  • 219
  • 2
  • 14
  • 1
    You have a definition of an array of char * named "words", but are printing from a variable named keyWords. Given your usage of `&keyWords[i]`, one would assume that keyWords is of a different type. If keyWords is of the same type (array of char *), then surely the compiler warned you that you are using it incorrectly. – William Pursell Oct 16 '19 at 14:39
  • 1
    Now would be **good time** to find out **where your IDE/compiler spits out all those warnings** – Antti Haapala -- Слава Україні Oct 16 '19 at 14:53
  • For an explanation of what was actually happening, see https://stackoverflow.com/a/7755280/10396 and https://en.wikipedia.org/wiki/Endianness – AShelly Oct 17 '19 at 20:42

2 Answers2

3

For starters use string literals instead of the character literals

const char *words[10] = {"foo", "bar", "hello", "world"};

Pay attention to that all elements of the array starting from the index 4 are initialized by null-pointers.

And just use

for(int i = 0; words[i] != NULL && i < 10; i++) {
        printf("Keywords: %s\n", keyWords[i]);
                                 ^^^^^^^^ 
    }

Here is a demonstrative program

#include <stdio.h>

int main(void) 
{
    const char *words[10] = {"foo", "bar", "hello", "world"};

    for ( size_t i = 0; words[i] != NULL && i < 10; i++ ) puts( words[i] );

    return 0;
}

Its output is

foo
bar
hello
world

Pay attention to that there is a typo in tour code snippet. Either use the name words or keywords for naming the array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Didn't really need this `words[i] != NULL &&` but changing those single quotes to double quotes fixed it. – LtMuffin Oct 16 '19 at 14:57
0

You should only use "&keywords" when you're writing a scanf, not a printf. Do the following:

printf("Keywords: %s\n", keyWords[i]);
Diogo Cruz
  • 77
  • 1
  • 14
  • on a side note, i don´t recommend that you do i<=9 when the array is , in this example, size=10. You should create a variable called size_array , initialize it as int size_array = sizeof(array) / sizeof(array[0]); and in the for cycle, use for(i=0, i – Diogo Cruz Oct 16 '19 at 14:50