question about calloc

What I find confusing about calloc is it takes two arguments. One is a number of elements and the second is the size of each element. So in the below example, we specify we want to allocate 1 element and its size is 256 bytes. Why not just allocate 256 without the need for the first argument? Is the first argument to calloc really needed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char cmd_0[]={
                0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
                0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
             };

int main(void)
{
   unsigned char *ask;

   // allocate a block of memory for 1 element, which is 256 bytes
   ask = (unsigned char*)calloc(1,256);
   memcpy(ask, cmd_0, sizeof(cmd_0));   

   printf("first element is %u\n", *ask);

   return 0;
}
Aha, so that's what that error was about. You must have deleted your topic while I was replying.

You are technically correct; there is no real need for two arguments since calloc() just allocates a contiguous block of num*size bytes. However it may be nicer for some to read something like this:
1
2
// I want space for 25 ints
calloc(25, sizeof(int));
that's a good an example of when to use both thanks
Topic archived. No new replies allowed.