问题描述
#include <stdio.h>
main()
{
char * ptr;
ptr = "hello";
printf("%p %s" ,"hello",ptr );
getchar();
}
我想清楚地了解如何获得阵列中分配的指针。当你指定字符数组来字符的指针,我注意到 PTR =你好;
数组衰变为指针,但在这种情况下,我分配的一个char数组是不是一个变量中,而不是变量包含他们,并转让这种方式需要一个内存地址专门为你好
(什么明显的事情),以及是有可能修改每个元素的值中的Hello至极被包含在其中,该数组存储在存储器地址。作为对比,它是细为我的指针分配与例如共整数的数组作为含糊,因为这东西 = INT_PTR 5,3,4,3;
和值5,3,4,3得到坐落在一个内存地址为你好一样。如果不是,为什么只能用字符串?在先进的感谢是有可能。
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.
推荐答案
你好
是一个字符串文字。它的类型是有一种无名的不可修改的对象的char [6]
。这是一个数组,它的行为方式相同的其他数组一样。事实上,它是无名并没有真正改变任何东西。你可以用 []
运营商使用它,例如,如你好[3]
等。就像任何其他的阵列,它能够而且将会衰减在大多数上下文指针。
"hello"
is a string literal. It is a nameless non-modifiable object of type char [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
int *p = (int []) { 1, 2, 3, 4, 5 };
在这种情况下,右手边是一个类型的无名对象 INT [5]
,它衰变到为int *
指针。复合文字是可以修改的,虽然,这意味着你可以做 P [3] = 8
,从而替换 4
与 8
。
In this case the right-hand side is a nameless object of type int [5]
, which decays to int *
pointer. Compound literals are modifiable though, meaning that you can do p[3] = 8
and thus replace 4
with 8
.
您也可以使用复合文字语法字符数组,做
You can also use compound literal syntax with char arrays and do
char *p = (char []) { "hello" };
在这种情况下,右手边是一个类型的可修改无名对象的char [6]
。
In this case the right-hand side is a modifiable nameless object of type char [6]
.
这篇关于C:数组的行为时,分配给指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!