Using const char*

I am writing some code in C++ to print a message using fprintf

Here is an example

void pr_desc(
    FILE*  stream,
    int       shift,
    const char*  desc) {

  const char*  format="%*s\e[0;37m%s\e[0m\n";
  fprintf(stream,format,shift,"",desc); 
}

I call it using

const char*  desc;  

desc="display susage";
pr_desc(stream, msgShift, desc); 

desc="prints some examples";
pr_desc(stream, msgShift, desc); 

desc="display this usage information";
pr_desc(stream, msgShift, desc);

I want to know how it is that I can change desc when I declared desc as const.

desc is not a constant pointer to char, but a pointer to a constant char.

If you want desc to be a constant pointer, write:

char * const desc;

If you want desc to be a constant pointer to a constant character, write:

 const char * const desc;
 

I need to use

const char * 

I am unsure what const char * means, because I can change desc.

You are mistaken. You have not declared desc as const. desc is a memory address and it can change. However, the char that the memory address points to cannot be modified through desc.

Read hergp's response carefully.

Since desc is not constant, you can assign a new memory address to it, which is what's happening with desc="string" . What you cannot do (even if the memory is dynamically allocated) is indirect through desc to modify a character, *desc='a' .

Regards,
Alister

1 Like

Got it :b: