www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/05/21/13:32:57

From: Vic <tudor AT cam DOT org>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Re-Mallocing an array...
Date: Wed, 20 May 1998 14:54:56 -0400
Organization: Communications Accessibles Montreal, Quebec Canada
Lines: 30
Message-ID: <35632700.4045@cam.org>
References: <6jv6s8$kn1 AT nnrp4 DOT farm DOT idt DOT net>
NNTP-Posting-Host: dialup-613.hip.cam.org
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Chia wrote:
> but this crashes.  How do I do this, then?
I don't know why this would crash. but to re-allocate an array, use
realloc.

void* realloc(void* old_array, size_t new_size);
you pass the old array, the new size and it gives you a new one.

#include <stdio.h>

int* p;
int i;

void main()
{
printf("\nAlloc: 10 ints\n");
p=malloc(10*sizeof(int));
for(i=0;i<10;i++) p[i]=i+i/2;

printf("Done filling array. the values are:\n");
for(i=0;i<10;i++) printf(" int #%d=%d",i,p[i]);
printf("\nRealloc: same array, 20 ints\n");

p=realloc(p,20*sizeof(int));
printf("filling new array places. the values are:\n");
for(i=10;i<20;i++) p[i]=i*2;
for(i=0;i<20;i++) printf(" int #%d=%d;",i,p[i]);

free(p);
}

- Raw text -


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