Understanding Memory Buffers In C

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?
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
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( )?
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
closed account (zb0S216C)
OK, thanks, Moschops.
Topic archived. No new replies allowed.