I encountered a problem while testing a code.I define a macro for obtaining the number of elements of an array as follows:
#define ARRAY_SIZE(arr) sizeof(arr) / sizeof(arr[0])
This macro works fine for counting the number of elements of an array whose initializers match the storage capacity(e.g. int buf[] = {1,2,3};
),but not very effective with arrays declared as : int buf[20] = {1,2,3};
Now i know counting array elements like these is pretty easy,but what about large number of elements? How do you count them? counting could be a killer,you know!
Consider the following code:
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE(arr) sizeof(arr) / sizeof(arr[0])
void g_strcat(void *_Dst, size_t dstSize, size_t bytes, const void *_Src, size_t srcSize);
int main(void)
{
int dst[20] = { 1,2,3 };
int src[] = { 4,5,6 };
size_t dstSize = 3; // dstSize = ARRAY_SIZE(dst) doesn't work
size_t srcSize = ARRAY_SIZE(src);
g_strcat(dst, dstSize, sizeof(int), src, srcSize);
size_t n, newSize = dstSize + srcSize;
for (n = 0; n < newSize; n++) {
printf("%d ", dst[n]);
}
putchar('\n');
return 0;
}
void g_strcat(void *_Dst, size_t dstSize, size_t bytes, const void *_Src, size_t srcSize)
{
memcpy((char *)_Dst + (dstSize * bytes), _Src, srcSize * bytes);
}