Mail Archives: djgpp/2000/04/09/07:52:30
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 -