When a function expects a char** parameters, it is not possible to pass a
char[][] variable, which should have allowed us to avoid dynamic memory
allocation. Merely casting the char[][] will produce undesirable
results. Example:
void iterate(char** a, count) {
for(int i=0; i<count; i="">
operate(a[i]);
}
}
int main () {
char str_array[32][128];
iterate((char**)(str_array), 32);
return 0;
}
The a[i] will reference (char*)str_array+sizeof(int), a lot different from what we want str_array[i].
However, we can do this:
int main() {
char buffer[32*128];
char* str_array[32];
for(int i=0; i< ++i) {
str_array[i] = buffer+i*128;
}
iterate((char**)str_array, 32);
return 0;
}
This will produce the desired effect
void iterate(char** a, count) {
for(int i=0; i<count; i="">
operate(a[i]);
}
}
int main () {
char str_array[32][128];
iterate((char**)(str_array), 32);
return 0;
}
The a[i] will reference (char*)str_array+sizeof(int), a lot different from what we want str_array[i].
However, we can do this:
int main() {
char buffer[32*128];
char* str_array[32];
for(int i=0; i< ++i) {
str_array[i] = buffer+i*128;
}
iterate((char**)str_array, 32);
return 0;
}
This will produce the desired effect
No comments:
Post a Comment