Vasilis G. Vasilis G. - 2 months ago 4x
C Question

Initializing an array with a pointer in c

When I run the code:

char *abc="Goodbye";
for(i=0; i<=7; i++){
printf("%c\n",*(abc+i)); }

it runs without problem, but when I run the following:

char *der={'a','a','a','a','a'};
for(i=0; i<=4; i++){
printf("%c\n",*(der+i)); }

it doesn't show the correct results and I receive warnings.

So why is this happening since
are arrays of chars?


{'a','a','a','a','a'} is not an array but an initializer list, and it can be used to initialize either an aggregate or a scalar.
(Yes, int x = {'a'}; is valid.)

If it's used to initialize a scalar, such as a pointer, only the first value is used, so your declaration of der is equivalent to

char *der = 'a';

You can probably see what the problem is.

So today's programming lessons:

  • When your compiler warns you that something might be wrong, it probably is.
    (Most experienced programmers treat warnings as errors, -Werr. It's an even more important habit for the inexperienced.)
  • If you don't understand what a warning means, don't do anything until you've found out.