Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const usage with pointers in C

Tags:

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.

like image 523
Scott Davies Avatar asked Sep 18 '09 18:09

Scott Davies


People also ask

Can we declare a pointer variable as constant in C?

We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.

What is constant pointer with example?

A pointer to constant is defined as : const <type of pointer>* <name of pointer> An example of definition could be : const int* ptr; Lets take a small code to illustrate a pointer to a constant : #include<stdio.h> int main(void) { int var1 = 0; const int* ptr = &var1; *ptr = 1; printf("%d\n", *ptr); return 0; }

What is the difference between constant pointer and pointer to constant?

In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.

Can pointer change const value?

const int * is a pointer to an integer constant. That means, the integer value that it is pointing at cannot be changed using that pointer.


1 Answers

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.

like image 169
sepp2k Avatar answered Oct 06 '22 00:10

sepp2k