Why declare pointer to array if arrays are already pointers?

Asked

Viewed 815 times

4

if an array char is already a pointer, why declare a pointer to the array?

And what’s the difference between char exemplo[10] and char *exemplo[10]?

  • You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? Something needs to be improved?

2 answers

6

An array char (or other type) IS NOT a pointer.

An array is an array; a pointer is a pointer (see Section 6 of c-Faq).

When an array is used as value, it is converted to a pointer to its first element.

The difference between char exemplo[10] and char *exemplo[10] is that the first declares a 10-character array and the second declares a 10-pointer array.

  • 1

    +1 by "A char array (or other type) IS NOT a pointer". I have seen several responses indicating: in the C language arrays do not actually exist, or that they are the same as pointers.

5

You nay is declaring a pointer to array. Is declaring a pointer to char. Ai contrary to popular belief they are separate things.

In the first example there is a array with 10 chars. In the second there is a array with 10 hands for char.

The pointer to char is practically a synonym for string. C language does not have the type string, but this is as close to a.

Obviously the pointer needs to point to an area of memory that has a sequence of chars.

  • 2

    A literal between quotation marks, in C, has an array of N characters in which N is sufficient for the characters of the literal and the terminator. "exemplo" has kind char [8].

  • @pmg is true, it decays to a const char * just. I fixed it.

  • 2

    When used as value, the array is converted to a pointer to its first element. In the case of literal string this conversion is to the type char * (nay const char *) although the result is read-only. To avoid surprises many people add the const specifically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.