I am reading 32 byte chunks from a file and storing them in a character array.
1. What is the difference in defining that array as:
char * buffer;
or...
char buffer[32];
They both behave the same at run time when I call:
result = fread(buffer, ElementSize, ArraySize, inFile);
I think the former is a pointer to an unbounded block of memory while the latter refers to the 32 bytes of allocated memory, correct?
2. If I'm iterating a file, reading a fixed amount of bytes each time then presumably it's preferable to use the latter fixed size buffer?
3. When I write the buffer out using cout it's dumping more characters than the 32 I asked for. I believe this is because cout will dump the buffer and keep going until a null character is found, correct?
4. To get around the problem in .3 I want to cout just the 32 bytes of information stored in buffer, how do I effectively do something like:
char* buffer is a pointer to a char. The size of buffer is the size of a pointer.
char buffer[32] is a contiguous block of 32 bytes of memory, an array. The size of buffer is 32.
if you use char* buffer, you must make it point to something. If you don't you have no idea what part of your memory is being overwritten. This is a very serious problem, and even though your program doesn't crash now, if it were large enough and ran long enough it would eventually crash and you'd really struggle to identify the cause.
Similarly, if you use char buffer[32], you must make sure you never write more than 32 bytes into that array.
You can declare your buffer like char buffer[33]; read 32 bytes from the file and then set the last char to zero like buffer[32]='\0'; (or buffer[32]=0; whatever you like), so that when you use cout it stops there. However you must be sure that there is no other '\0' char inside your buffer or the printing will stop there... (I don't know what kind of data you're reading from your file). If you're not sure, you can always resort to the solution of using a for loop with the loop variable iterating through the size of your buffer and print one character in each iteration.
Also heed kbw's advice and use an array instead of a pointer as a buffer.