Understanding Memory Buffers In C

Feb 20, 2011 at 10:19pm
closed account (zb0S216C)
I'm trying to figure out how buffers work in C. First off, I'm trying to create a buffer which holds integers. The thing is, I don't know how to access values in the buffer. I was thinking about using calloc( ) instead of malloc( ).

Here's my current code:
1
2
3
4
5
6
7
8
9
10
11
#include <cstdlib>

int main( )
{
    int *Buffer( ( int * )malloc( sizeof( int ) ) );

    free( Buffer );
    Buffer = NULL;

    return 0;
}


How do I access the value( s ) within the buffer?
Feb 20, 2011 at 10:35pm
Buffer[i], where i is the element you want (remember that the first element is element zero).

In C++ consider using new instead of malloc.

In this case, you have allocated enough memory for one int only, so it's Buffer[0] and nothing else.
Last edited on Feb 20, 2011 at 10:37pm
Feb 20, 2011 at 10:37pm
closed account (zb0S216C)
So basically, I'm accessing elements in the buffer like an array using the subscript operator? So what is the difference between calloc( ) and malloc( )?
Feb 20, 2011 at 10:40pm
malloc takes a single parameter and allocates that many bytes.

calloc takes two parameters and allocates a number of bytes equal to their product, and sets the whole lot to zero.

Buffer[i] is identical to *(Buffer + i), which is identical to *(i + Buffer) and also i[Buffer]
Last edited on Feb 20, 2011 at 10:41pm
Feb 20, 2011 at 10:41pm
closed account (zb0S216C)
OK, thanks, Moschops.
Topic archived. No new replies allowed.