Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C arrays

Name: Anonymous 2008-11-15 10:18

is there a way to do this all in one function instead of splitting it into two?
#include <stdlib.h>

void stuff_with_a(char a[20000000][20]){
 for(int i = 0; i < 20000000; ++i){
  for(int j = 0; j < 20; ++j)
   a[i][j] = 0;
 }
}

int main(){
 char *a = malloc(20000000*20);
 stuff_with_a(a);
 sleep(60);
 return 0;
}

Name: Anonymous 2008-11-15 10:43

1. Just use memset


#define N 2000000*20
char *a = malloc(N);
memset((void *)a, 0, N);


2. Anyway you are doing it wrong.

The formal parameter of the stuff_with_a function declares at stack level a huge matrix, while the correct way of doing this is using pointers.

Just try to compare assembly code obtained by the following versions of the same function:


void foo(char **x, size_t n, size_t m) {
    uint32_t i,j;
    for (i=0; i<n; i++)
        for (j=0; j<m; j++)
            x[i][j] = 0;
}



void foo(char x[1000][10]) {
    uint32_t i,j;
    for (i=0; i<1000; i++)
        for (j=0; j<10; j++)
            x[i][j] = 0;
}


You will notice that the first version is much more good!

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List