PDA

View Full Version : Add elements to an array.



R0b0t1
12-22-2007, 05:28 AM
I'm reading a file character by character, and I want to add an element to a character array to place the new input in... this is what I have so far.



fileText = realloc(fileText, sizeof(char)*((sizeof(fileText)/(sizeof(char)))+sizeof(char)));


Anyone have a better idea/fix?


EDIT: What this does is the size of a char * number of elements in the array + the length of one byte. Will this work?

BenLand100
12-23-2007, 04:19 AM
HOLY CRAP NO!!!
You are going to realloc an array for each character in a FILE? No. Find a better way. ;)
Anyway, just for kicks, a char is always one byte, and the sizeof fileText (being a pointer in a 32 bit system) is always 4 (remember, size of the variable, not what it points to), thus:
fileText = realloc(fileText, 1*(4/1)+1));
Or:
fileText = realloc(fileText, 5);
So it won't work anyway ;)

R0b0t1
12-24-2007, 02:41 AM
Oh.

Uhmm... Ohhhhkaaay.... How much space should I leave for each file then? allocate 1 meg at the begining and free it later?

BenLand100
12-24-2007, 04:41 AM
Oh.

Uhmm... Ohhhhkaaay.... How much space should I leave for each file then? allocate 1 meg at the begining and free it later?
Its OK to realloc sometimes, but not in 1 byte increments, that will be really, really slow. ;) Isn't there a way to read the file size before you get the data? Why not allocate the size of the file and leave it at that?

R0b0t1
12-24-2007, 07:54 PM
Sure. That will work...