Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!lll-crg!styx!ames!ucbcad!ucbvax!decvax!mcnc!rti-sel!dg_rtp!throopw From: throopw@dg_rtp.UUCP (Wayne Throop) Newsgroups: comp.lang.c Subject: Re: help needed about dynamic space allocation Message-ID: <715@dg_rtp.UUCP> Date: Tue, 25-Nov-86 17:29:23 EST Article-I.D.: dg_rtp.715 Posted: Tue Nov 25 17:29:23 1986 Date-Received: Wed, 26-Nov-86 19:58:36 EST References: <13802@amdcad.UUCP> <359@prairie.UUCP> <1046@lifia.UUCP> Lines: 57 > fano@lifia.UUCP (Rampa*) > I need advice on dynamic space allocation for multidimensionnal arrays: Well... a little maybe. > float **sig; /* matrix declaration */ > sig = (int *)malloc(n * sizeof(int)); /* allocates space for sig */ OK. Stop right here for a minute. What's wrong with this picture? It is a little subtle, perhaps, but a pointer value of type (int *) is being assigned to a pointer of type (float **). Does anybody really not see anything wrong with this? Hmmmmmm? Can you say "illegal pointer combination"? I knew you could. Lint can say it too. Let's say it together, boys and girls... (oh all right, I know I'm being nasty... I'll behave myself the rest of the posting, alright?) To fix this, make the allocation read: sig = (float **)malloc(n * sizeof(float *)); > sig[i] = (float *)malloc(n * sizeof(float)); /* allocate a column */ This one is already correct. > free(sig[i]); /* desallocates space */ Should be: free((char *)sig[i]); > free(sig); Should be: free( (char *)sig ); > during the compiling time, I get the following warning: > "combin1.c", line 220: warning: illegal pointer combination > any-way the program runs, and gives the desired results. The program will run correctly on systems where integers have the same length as pointers to float, and where pointers to float have the same format as pointers to char. I don't know what kind of system that would be. Maybe... oh, I don't know... could it be... *A* *VAX*???? (Isn't that special? :-) > The compiler message suggests that I didn't use the proper way to implement > matrix dynamic allocation. So, could someone over there give me advices for > a cleaner solution. In fact, the program seemed quite clean and well written already, except for the pointer type mismatches and the hidden assumption about the size of floats and ints. Fix that, and the program should still work, and lint will shut up also... who could ask for more? -- A programming language is low level when its programs require attention to the irrelevant. --- Alan J. Perlis -- Wayne Throop !mcnc!rti-sel!dg_rtp!throopw