To reallocate an array ?

E

erktek

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
int i;
int a[1];
int *p = NULL;

p = a;

p = (int *) realloc(p,3*sizeof(int)); // here the code crashes ?

p[0] = 1;
p[1] = 2;
p[2] = 3;

for (i=0; i < 3;i++)
printf("%d\n",p);

free(p);

return 0;
}

The code above crashes ? What is the reason ?
Isn't it possible to reallocate the array "a" again via pointer p ?
 
R

Richard Bos

The code above crashes ? What is the reason ?
Isn't it possible to reallocate the array "a" again via pointer p ?

In a word: no. realloc() (which, btw, does not take a cast in
well-written C code) only works on null pointers or previously allocated
pointers, not on arrays, pointers to normal objects, or pointers which
have had arithmetic done on them.

Richard
 
W

WaterWalk

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
int i;
int a[1];
int *p = NULL;

p = a;

p = (int *) realloc(p,3*sizeof(int)); // here the code crashes ?

p[0] = 1;
p[1] = 2;
p[2] = 3;

for (i=0; i < 3;i++)
printf("%d\n",p);

free(p);

return 0;

}

The code above crashes ? What is the reason ?
Isn't it possible to reallocate the array "a" again via pointer p ?


realloc only works with pointers whose pointed to memory is allocated
dynamically, for example using malloc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,501
Latest member
Ledmyplace

Latest Threads

Top