As caf talked about it in https://stackoverflow.com/a/1113041/1354779,
there is a way to use initialisers when the variable is declared to initialize an array already declared.
That is great, and I now would like to know if there is a way to use every item of the array, one by one.
I use that to pass on a list of commands through a pipe, and I know that this works:
char* script[]={"report blabla","report bla"};
char line[200];
char** command;
for (command = script ; **command ; **command ? command++ : 0){
if (**command){
SendCommand(*command, line, sizeof(line));
}
}
But when I try my code below, I get an “Unhandled exception at 0x778915de in pipe_GWB9.exe: 0xC0000005: Access violation reading location 0xcccccccc” :
char* request[] = {"report watact"};
char line[200];
// [...] Other code [...]
static const char *tmp[8] =
{
"report molality H+",
"report molality Cl-",
"report molality Ca++",
"report molality Mg++",
"report molality K+",
"report molality Fe++",
"report molality SO4--",
"report molality Na+"
};
memcpy(request, tmp, sizeof request);
char** command;
command=request;
SendCommand(*command, line, sizeof(line));
// Until here, everything works great.
**command ? command++ : 0;
SendCommand(*command, line, sizeof(line));
// But THAT doesn't work!!
Would you be able to help me calling for the other items of the array request?
Thanks
requestis an array of pointers to char which contains 1 element.tmpis an array of pointers tocharwith 8 elements.You copy the first four bytes (assuming
sizeof request == 4) fromtmpintorequest, i.e., you copy the first element oftmpinto the first element ofrequest.Simple enough;
commandnow points to the first (and only!) element ofrequest.Oops. You just ran past the bounds of
command(request) becauserequestcontains only a single element. You then dereference it when callingSendCommandon the next line, which gives you your seg fault. Note that anything could happen here because you are invoking UB.For example, what may happen if you cut out the code between the two arrays is that the string
"report molality H+"is sent twice because incrementing the pointer past the bounds ofrequestmay very well just plop you onto the beginningtmp.If you want to copy all of
tmpintorequestthen you need to make sure the two arrays are of the same size (or at least, thatrequestis as large astmp).As an aside, this ternary expression is a bit silly:
You only care about one branch, so why use a ternary at all? Prefer:
That said, this is not a safe way to check the bounds of your array (as you found out). You are treating the array of pointers as if it were a pointer to char, i.e., scan until you find the NULL terminator.
There is no NULL terminator for an array, you simply end up walking past its boundaries and invoking undefined behavior, so you need to keep track of the size separately and check against that.