www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/01/12/13:21:37

From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: array casting
Date: 12 Jan 2001 17:53:14 GMT
Organization: Aachen University of Technology (RWTH)
Lines: 39
Message-ID: <93ngaa$orf$1@nets3.rz.RWTH-Aachen.DE>
References: <3A5F2E12 DOT 9A6C50FC AT ma DOT tum DOT de>
NNTP-Posting-Host: acp3bf.physik.rwth-aachen.de
X-Trace: nets3.rz.RWTH-Aachen.DE 979321994 25455 137.226.32.75 (12 Jan 2001 17:53:14 GMT)
X-Complaints-To: abuse AT rwth-aachen DOT de
NNTP-Posting-Date: 12 Jan 2001 17:53:14 GMT
Originator: broeker@
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

[This is a basic C question, and thus had better been asked in
comp.lang.c or de.comp.lang.c]

Waldemar Schultz <schultz AT ma DOT tum DOT de> wrote:

> int poly(int n, int data[][2]);
> void do_poly(int n)
> {
> int **data=malloc(... n);
>  poly(n, data); //call the function
> }
> and of course GCC warns me about the parameter type mismatch.

Arrays-of-arrays are one of the cases where the fundamental
incorrectness of the often-heard statement that "arrays are the same
as pointers to their first elements" shows through. The above code
snippet is faulty, and the GCC warning is very well justified.

You should have done this, instead:

	int (*data)[2] = malloc(n * sizeof (*data))

'data' is a pointer to an array of 2 ints now, not a pointer to
pointer to int.  This type is compatible to the argument of poly(),
yours isn't.  

The underlying problem is that the storage described by an int [n][2]
is guaranteed by the C language to be in a single, contiguous block of
exactly 2*n*sizeof(int) bytes, whereas the storage behind an int **
can be fragmented into n separate hunks, with no way of telling how
large each of them is.

Another error in what you showed of your code: you only allocate
memory to hold the pointers-to-pointer-to-int themselves, but not the
pointers-to-int they are supposed to point to.

-- 
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019