#include <stdio.h>
main()
{
char * ptr;
ptr = "hello";
printf("%p %s" ,"hello",ptr );
getchar();
}
Hi, I am trying to understand clearly how can arrays get assign in to pointers. I notice when you assign an array of chars to a pointer of chars ptr="hello"; the array decays to the pointer, but in this case I am assigning a char of arrays that are not inside a variable and not a variable containing them “, does this way of assignment take a memory address specially for "Hello" (what obviously is happening) , and is it possible to modify the value of each element in “Hello” wich are contained in the memory address where this array is stored. As a comparison, is it fine for me to assign a pointer with an array for example of ints something as vague as thisint_ptr = 5,3,4,3; and the values 5,3,4,3 get located in a memory address as “Hello” did. And if not why is it possible only with strings? Thanks in advanced.
"hello"is a string literal. It is a nameless non-modifiable object of typechar [6]. It is an array, and it behaves the same way any other array does. The fact that it is nameless does not really change anything. You can use it with[]operator for example, as in"hello"[3]and so on. Just like any other array, it can and will decay to pointer in most contexts.You cannot modify the contents of a string literal because it is non-modifiable by definition. It can be physically stored in read-only memory. It can overlap other string literals, if they contain common sub-sequences of characters.
Similar functionality exists for other array types through compound literal syntax
In this case the right-hand side is a nameless object of type
int [5], which decays toint *pointer. Compound literals are modifiable though, meaning that you can dop[3] = 8and thus replace4with8.You can also use compound literal syntax with char arrays and do
In this case the right-hand side is a modifiable nameless object of type
char [6].