Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* const args[] definition [duplicate]

I'm having trouble understanding the usage of const here:

char* const args[]; 

does that mean args cannot point to a new address? How is it different from:

const char* args[];

Also I'm trying to traverse through this list and append the values to a string using a single for loop statement:

string t_command;
for(char** t= args; (*t) != NULL ; t++ && t_command.append(*t + " ")) {}

I'm not doing something right here and I can't figure out what.

like image 403
ArmenB Avatar asked Jul 04 '26 08:07

ArmenB


1 Answers

char* const args[]; 

args is an array. Each element in the array is a pointer to char. Those pointers are const. You cannot modify the elements of the array to point anywhere else. However, you can modify the chars they point at.

const char* args[]; 

args is still an array. Each element in the array is still a pointer to char. However, the pointers are not const. You can modify the elements of the array to point elsewhere. However, you cannot modify the chars they point at.

Diagram time:

Args:
┌───┬───┬───┬───┬───┬───┐
│   │   │   │   │   │   │  // In the first version, these pointers are const
└─╂─┴─╂─┴─╂─┴─╂─┴─╂─┴─╂─┘
  ┃   ┗━┓ ┗━┅ ┗━┅ ┗━┅ ┗━┅
  ▼     ▼
┌───┐ ┌───┐
│ c │ │ c │                // In the second version, these characters are const
└───┘ └───┘

Often, when you have a pointer to characters, those characters are part of an array themselves (a C-style string), in which case it looks like this:

Args:
┌───┬───┬───┬───┬───┬───┐
│   │   │   │   │   │   │  // In the first version, these pointers are const
└─╂─┴─╂─┴─╂─┴─╂─┴─╂─┴─╂─┘
  ┃   ┗━━━━━━━┓   ┗━┅ ┗━┅
  ▼           ▼
┌───┬───┬┄  ┌───┬───┬┄
│ c │ c │   │ c │ c │      // In the second version, these characters are const
└───┴───┴┄  └───┴───┴┄

As for traversing through the array, you are attempting to treat the args array as null-terminated. That's not how most arrays work. You should iterate using an index into the array.

Also note that you cannot add an array and a string literal together (as in *t ++ " "). Convert one side to a std::string to make it much easier.

So if N is the size of args:

for (size_t i = 0; i < N; i++) {
  t_command.append(std::string(args[i]) + " "))
}
like image 139
Joseph Mansfield Avatar answered Jul 07 '26 00:07

Joseph Mansfield