delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/04/09/07:52:30

From: Chris Mears <cmears AT bigpond DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: arrarys
Organization: only if absoultely necessary
Message-ID: <g8q0fscsb0piv02c17ibmm4sq81fheelvr@4ax.com>
References: <5ZtG4.648$OR3 DOT 8963 AT typhoon DOT nyroc DOT rr DOT com> <8ci6hc$di5$1 AT news DOT koti DOT tpo DOT fi>
X-Newsreader: Forte Agent 1.8/32.548
MIME-Version: 1.0
Lines: 61
Date: Sun, 09 Apr 2000 21:31:50 +1000
NNTP-Posting-Host: 139.134.196.99
X-Trace: newsfeeds.bigpond.com 955279474 139.134.196.99 (Sun, 09 Apr 2000 21:24:34 EST)
NNTP-Posting-Date: Sun, 09 Apr 2000 21:24:34 EST
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

On Thu, 6 Apr 2000 17:33:47 +0300, that hoopy frood "Ilari Kaartinen"
<ililka AT mantta DOT fi> wrote:

>You didn't give enough information to answer this question.
>So, I assume that you are using C.
>
>Bob <fubu36 AT stny DOT rr DOT com> wrote in message
>news:5ZtG4.648$OR3 DOT 8963 AT typhoon DOT nyroc DOT rr DOT com...
>> if a array is delcared such as "int number[19];"
>> is there anyway to later change it so that it keeps all of the original
>> values but can hold an addition 1,5,or any addition numbers?
>>
>>
>
>/* clip clip */
>#include <stdio.h>
>#define SIZEOFARRAY 19
>#define ADDME 5
>
>int main(void)
>{
>int* array = (int*)malloc(sizeof(int)*SIZEOFARRAY);

Oh dear.  You have just caused a freak storm off the coast of South
America.  This line causes undefined behaviour.  malloc(), as defined
by the C standard, returns a pointer to void.  Since you haven't
provided a prototype (there's a nice one in <stdlib.h>, by the way),
it is assumed that malloc() returns int.  The types "int" and "void*"
aren't compatible.

Under most circumstances, the compiler would spit out a warning.  Not
this time, because you cleverly used a cast.  Casts are the work of
the devil.

Also, it might be better to use:
int* array = malloc(sizeof *array * SIZEOFARRAY);

This way, if the type of "array" ever changes, you won't need to
change the "sizeof (int)" to reflect the new type.

>if(array == NULL)
>    return 1;
>
>/* this is what you wanted */
>array = (int*)realloc(array,sizeof(int)*(SIZEOFARRAY+ADDME));

Again, lose the cast.

>
>free(array);
>
>return 0;
>}
>/* clip clip */


-- 
Chris Mears

cmears AT bigpond DOT com
ICQ: 36697123

- Raw text -


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