Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding of strlen function - Assignment of const char *s to const char *sc

Below is the implementation of strlen.c as per "The Standard C Library,

size_t strlen(const char *s){
   const char *sc;
   for(sc = s; *sc != '\0'; ++sc)

   return (sc-s);  }

Is my understanding of the legality of sc = s correct?

sc=s is a legal assignment because since both variables are declared as const, both protect the object that is pointed to by s. In this case, it is legal to change where sc or s both point to but any assignment (or reference?) to *s or sc would be illegal.

like image 435
M.A.A Avatar asked Jan 01 '23 10:01

M.A.A


1 Answers

I think what you are asking is what the const keyword means. If not please clarify your question.

The way I like to think of it is any const variable can be stored in ROM (Read Only Memory) and variables that are not declared const can be stored in RAM (Random Access Memory). This kind of depends on the kind of computer you are working with so the const data may not actually be stored in ROM but it could be.

So you can do anything you want with the pointer itself but you can not change the data in the memory it points to.

This means you can reference the pointer and pass that around as much as you like. Also you can assign a different value to the pointer.

Say you have this code

const char* foo = "hello";
const char* bar = "world";

Its perfectly legal to do

foo = bar;

Now both point "world"

Its also legal to do

const char *myPtr = bar;
myPtr = foo;

What you are not allowed to do is change the actual data memory so you are not allowed to do

foo[0] = 'J';
like image 189
Marc Avatar answered Jan 29 '23 18:01

Marc