Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

const usage with pointers in C

I am going over C and have a question regarding const usage with pointers. I understand the following code:

const char *someArray

This is defining a pointer that points to types of char and the const modifier means that the values stored in someArray cannot be changed. However, what does the following mean?

char * const array

Is this an alternate way of specifying a parameter that is a char pointer to an array named "array" that is const and cannot be modified?

Lastly, what does this combination mean:

const char * const s2

For reference, these are taken from the Deitel C programming book in Chapter 7 and all of these are used as parameters passed to functions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

const char* is, as you said, a pointer to a char, where you can't change the value of the char (at least not through the pointer (without casting the constness away)).

char* const is a pointer to a char, where you can change the char, but you can't make the pointer point to a different char.

const char* const is a constant pointer to a constant char, i.e. you can change neither where the pointer points nor the value of the pointee.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...