SRL Archive - C/C++ Help and Tutorials

Add elements to an array.


R0b0t1

2007-12-22 00:28:59

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

2007-12-22 23:19:52

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

2007-12-23 21:41:56

Oh.

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

BenLand100

2007-12-23 23:41:10

From: R0b0t1
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

2007-12-24 14:54:19

Sure. That will work…