C/C++ Programming Tips and Tricks

Wednesday, February 01, 2006

char** from static variables

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

Wednesday, January 18, 2006

Optimization by loop re-factoring

Instead of:

for(int i = 0; i < MAX; ++i)
if(i != ID)
{
// DO SOMETHING
}
}

Use:

for(int i = 0: i < ID; ++i)
{
// DO SOMETHING
}
for(int i = ID; i < MAX; i="">
{
// DO SOMETHING
}