MESSAGE
DATE | 2004-09-09 |
FROM | Billy
|
SUBJECT | Re: [hangout] Re: two dimensional arrays passed to functions
|
On Thu, Sep 09, 2004 at 02:50:58PM -0400, Ruben Safir Secretary NYLXS wrote: > > >The right way to do it: > > > > char * insert(char *table, int cols, char **values); > > This just won't take in example codes or in the main program I'm > writing. It compiles but segfaults. This is what I statrted with > which has put me on 2 days of a twisted path. > ...
> Even worse, it seems C's implementaitons for 2 dimensional arrarys is > nothing for of inconsistent. Things I've read that I should be able > to do, simple don't work.
The decay of arrays into pointers seems inconsistent because it is non-recursive, as the FAQ says.
> Look at this sample program, for example: > > #include > #include > #include > #include > > void print_str(char **b); > #define ARRAY_COUNT(a) (sizeof(a)/sizeof(a[0])) > > int main(int argv, char *argc[]){ > char a[3][256]; > > strcpy(a[0], "Ruben"); //a[0] converted to char*: a[0] => (char*)a + 1*sizeof(a[0]); > strcpy(a[1], "Safir"); //a[1] converted to char*: a[1] => (char*)a + 1*sizeof(a[0]); > strcpy(a[2], "222222"); //a[2] converted to char*: a[2] => (char*)a + 2*sizeof(a[0]); > printf("\n%s", a[0]); // same here... > printf("\n%s", a[1]); // and here... > printf("\n%s", a[2]); // and here... > { > char *arows[ARRAY_COUNT(a)]; > int i; > for(i=0;i> arows[i] = a[i]; > print_str(arows); // ok > } > print_str(a); // now you're in trouble. > // the compiler CAN'T convert 'a' into (char**). > // this would require allocating and filling a > // temp like the 'arows' above. > // print_str isn't psychic and can't tell > // anything about a's layout. > exit(0); > } > > void print_str( char **b ){ > printf("\n%s", *b); > b++; > printf("\n%s", *b); > b++; > printf("\n%s\n", *b); > return; > } > > > ruben-at-flatbush:~> gcc -Wall test_func.c test_func.c: In function `main': > test_func.c:21: warning: passing arg 1 of `print_str' from incompatible > pointer type > > It segfualts and according to the literature, it is the wrong pointer > type because it is only a char *[255] and not a char**
Right. And what did you expect? print_str isn't expecting a pointer to an array of chars (which is what you're giving it). It's expecting an array of pointers. Not at all the same thing.
You're confusing yourself. Just forget about passing arrays.
> >Advice: don't use arrays as arguments. It's stupid. Use pointers. > > I'm wishing I can take this advise!
Of course you can! ____________________________ NYLXS: New Yorker Free Software Users Scene Fair Use - because it's either fair use or useless.... NYLXS is a trademark of NYLXS, Inc
|
|