If arrays decay into a pointer shouldn't char string[] = "Hello"
also point to the first element like char* string = "Hello"
or char *(string) = "Hello"
.
Asked
Active
Viewed 60 times
-1

Paralax01
- 63
- 4
-
`char string[] = "Hello"` doesnt 'point' anywhere, its just a declaration – pm100 Mar 07 '22 at 21:31
-
If you use `string` in a context where it decays to a pointer, it will point to the first element. E.g. `printf("%s", string);` – Barmar Mar 07 '22 at 21:32
-
2C 2018 6.3.2.1 3 specifies three exceptions to the automatic conversion of an array to a pointer: It is the operand of `sizeof` (so `sizeof "Hello"` gives the number of bytes in the array, 6, including the terminating null character), it is the operand of unary `&` (so `&"Hello"` gives a pointer to the array, similar to a pointer to its first element except its type is “pointer to array of 6 `char`” instead of “pointer to `char`”), or it is a string literal used to initialize an array (so `char string[] = "Hello"` initializes the array with the contents of the string instead of its address). – Eric Postpischil Mar 07 '22 at 21:56
-
And where you want to point? To 5th element or 10th? – i486 Mar 07 '22 at 22:18
-
@i486 I mean when declared, it automatically decays into a pointer and points to the first element – Paralax01 Mar 07 '22 at 22:35
-
@EricPostpischil Interesting that `_Alignof` is not in the list of [3](https://stackoverflow.com/questions/71387488/do-arrays-always-point-to-the-first-element#comment126182044_71387488). `_Alignof` some_array also does not convert the array to a pointer. `_Alignof` some_array is the alignment needs of the array element type. § 6.5.3.4 3. – chux - Reinstate Monica Mar 07 '22 at 22:58
-
@chux-ReinstateMonica: The operand of `_Alignof` can only be a type in parentheses, not an object. (There may have been some error about this in C 2011.) – Eric Postpischil Mar 07 '22 at 23:05
-
@Paralax01 It is like label in assembler - its value is known to compiler. No need to generate pointer if you think about this. – i486 Mar 08 '22 at 11:27
-
@Eric Postpischil why is it the case `&"Hello` or generally `&array` gives a pointer to its first element, even if the array name isn't a pointer to its first element – Paralax01 Mar 10 '22 at 03:12
1 Answers
0
The first one dcays too
#include <stdio.h>
int main() {
char string[] = "Hello";
printf("First char = %c", *string);
}
gives
First char = H

pm100
- 48,078
- 23
- 82
- 145
-
OK. I had only read the question and answer and did not even notice your comment under the question. Answer would better stand without needing to infer things from the comment discussion you had with OP. – chux - Reinstate Monica Mar 07 '22 at 23:14