sizeof help

B

bob

how can I get the size of this 'buffer':

FILE *filestream;
filestream = fopen("testFile.txt", "r+"};
char *buffer;
size_t count;
fseek(filestream, 0, SEEK-END);
count = ftell(filestream) + 1;
rewind(filestream);
buffer = (char*) malloc(count);
printf("buffer size: %d\n", sizeof buffer);

I keep getting 4, for the pointer. which actually makes sense .. I
think. So how can I find out the size of the 'buffer' that buffer
points to?

Also one more question.

size_t itemsize = sizeof(char);
size_t returnvalue;
returnvalue = fread(buffer,itemsize, count, filestream);
printf("fread returns: %d\n", returnvalue);
printf("fread read filestream into buffer, see: %s\n", buffer);

The final printf function won't work rigth, unless I add one more byte
to the buffer...i.e.

count = ftell(filestream) + 1;

as I did above. Why do I have to add 1 more byte?
 
I

Ivan Vecerina

: how can I get the size of this 'buffer':
:
: FILE *filestream;
: filestream = fopen("testFile.txt", "r+"};
: char *buffer;
: size_t count;
: fseek(filestream, 0, SEEK-END);
: count = ftell(filestream) + 1;
: rewind(filestream);
: buffer = (char*) malloc(count);
: printf("buffer size: %d\n", sizeof buffer);
:
: I keep getting 4, for the pointer. which actually makes sense .. I
: think. So how can I find out the size of the 'buffer' that buffer
: points to?
You can't -- in C, with malloc, the caller is responsible to
remember the size of the memory block that it has allocated.

In C++, you should use #include <vector> and write:
std::vector<char> buffer;
...
buffer.resize( count ); // instead of malloc
printf("buffer size: %d\n", (long)buffer.size() );
//or better:
// std::cout<<"buffer size: "<<buffer.size()<<'\n';

: Also one more question.
:
: size_t itemsize = sizeof(char);
: size_t returnvalue;
: returnvalue = fread(buffer,itemsize, count, filestream);
: printf("fread returns: %d\n", returnvalue);
: printf("fread read filestream into buffer, see: %s\n", buffer);
:
: The final printf function won't work rigth, unless I add one more byte
: to the buffer...i.e.
: count = ftell(filestream) + 1;
:
: as I did above. Why do I have to add 1 more byte?

As you used it, printf expects a zero-terminated string.
Again, a better way is:
std::cout.write( &buffer[0], buffer.size() );
 
A

Audison.Athena

when the type of operand expression of sizeof operator is an array
type, the result is the total number bytes in the array(the size of an
array of n elements is n times the size of an element). however here
the type of the operand expression is pointer to char, not
char[constant-expression].
 

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

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,147
Latest member
CarenSchni
Top