
May 30th, 2003, 10:51 AM
|
|
Junior Member
|
|
Join Date: May 2003
Posts: 24
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
|
realloc and pointers are driving me crazy!!
I have this code, and the problem is that every time I add a new element to my big list, i keep overwriting what I had before, and the tail never moves to the end of the list...........does anyone know what I am doing wrong?? Please help because I have looked at this thing too long, and I can't figure it out...it might be really simple.......thanks very much in advance...............
#include <stdlib.h>
typedef struct{
int num;
int val;
}blah;
void printBig(blah * start, blah * end, int size); //prints a list of blah variables
void printOne(blah T); //prints one blah varaible
int main()
{
blah * big=NULL; //head of list of blahs
blah * bigTail; //tail of list of blahs
blah * bigptr; //another pointer
int i=0;
int bigsize=0; //total size of big
int onesize=sizeof(blah); //size of one blah
blah temp;
while(i<3)
{
temp.num = i+10;
temp.val = i+10;
bigsize += onesize; //recalculate size of big
big = realloc(big, bigsize); //allocate that much space for the big
bigTail = big + bigsize - onesize; //make tail point to end of list - size of one
//blah
memcpy(bigTail, &temp, onesize); //copy this blah to list
bigTail += onesize; //adjust tail
i++;
}
printBig(big, bigTail, onesize); //print list
return 0;
}
void printBig(blah * start, blah * end, int size)
{
int i;
blah * head = start;
blah * tail = end;
printf("{ \n");
while(start!=end)
{
printOne(*start);
start+=size;
}
printf(" }\n");
}
void printOne(blah T)
{
int i;
printf("(%d, %d) ", T.num, T.val);
}
|