0

I can't understand why this piece of code works:

int main() {

    char *a = "Hello";
    printf("this is %s      ",a);

    int i = 0;

    for (i = 0; a[i] != '\0'; i++)
        printf("this is : %c    ",a[i]);
}

My questions are:

  1. in the FOR loop, why can I refer to the *a as an array?

  2. is/where it more advisable to use an array to represent a an array or a pointer.

Thank you for your help.

Mike

Saxtheowl
  • 4,136
  • 5
  • 23
  • 32
user159348
  • 21
  • 3
  • 5
    I would recommend picking up a [good book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) instead of randomly asking about basic language features. They should explain why you can do `a[i]` with a pointer. – Blaze Sep 27 '19 at 07:20
  • Question 2 is totally unclear to me. – Jabberwocky Sep 27 '19 at 07:23

1 Answers1

3

In C all literal strings are really arrays of characters including the null-terminator. And as an array, it of course can decay to a pointer to its first element.

So when you do

char *a = "Hello";

you initialize a to point to the first element of that array (i.e. first character in the string).

You could think of it something like

char compiler_internal_array[] = "Hello";

char *a = &compiler_internal_array[0];

Also, for any array or pointer a and index i, the expression a[i] is exactly equal to *(a + i). So any array indexing is really pointer arithmetic and pointer dereference.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Maybe apply `const` to `char compiler_internal_array[]` since string literals are readonly as you said? – Trickzter Sep 27 '19 at 07:28
  • 1
    @Trickzter That's problematic since string literal arrays *aren't* `const`, but they should be considered read-only since attempting to modify one leads to undefined behavior. Removed that part from my answer. – Some programmer dude Sep 27 '19 at 07:31
  • Learning something new every day, thanks! – Trickzter Sep 27 '19 at 07:33