简体   繁体   中英

question regarding pointer in c language

char *sample = "String Value";

&sample is a pointer to the pointer of "String Value"

is the above statement right?

If the above statement right, what is the equivalent of &sample if my declaration is

char sample[] = "String Value"

In the first one, there are two objects being created.

One is a char * (pointer-to-char) called sample , and the other is an unnamed array of 13 chars containing the characters of the string. In this case, &sample gives the address of the object sample , which is the address of a pointer-to-char - so, a pointer-to-pointer-to-char.

In the second example, there's only one object being created; an array of 13 chars called sample , initialised with the characters of the string. In this case, &sample gives the address of the object sample - so, a pointer-to-array-of-13-chars.

In the second example, there is no "equivalent" to &sample in the first example, in the sense of a pointer-to-pointer-to-char value. This is because there is no pointer-to-char value to take the address of. There is only the array.

在第一部分&sample中将返回创建的'sample'指针的地址,在第二种情况下将返回作为object创建的字符串的起始地址。

While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precaustions using pointers to prevent errors. We should make sure that we know where each pointer is pointing in a program. Here are some general observations and common errors that might be useful to remember. *ptr++, *p[],(ptr).member

In C arrays and pointers are more or less interchangable. You can treat an array name like it is a pointer, and a pointer like it is an array name.

If you take the address of ( & ) of a pointer, of course you get a pointer to a pointer.

&sample is the address of the pointer that points to "String Value".

For the second example, since an array name that is not followed by a subscript is interpreted as the pointer to the initial element of the array, which means

sample

and

&sample[0]

are the same, therefore &sample is also the address of the pointer that points to the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM