for
int *p;
sizeof(p) will always be non-50.
.... sizeof(p) will give the size of the pointer. The pointer size will not be changed after the call to malloc(). To ensure malloc() successfully allocated the requested space, check pointer p for NULL like so:
int *p;
p = (int*)malloc(50 * sizeof(int));
if(p == NULL)
{
printf("Allocation error!\n");
return 0;
}
Note however, that _if_ you had said:
int p[50];
printf("sizeof(p) is %d\n", sizeof(p));
//// .... that will give a different output...more like you expected.
The difference is static vs dynamic memory allocation....
As for your code, I don't see anything absolutely wrong (other than you don't ck the pointer for failed memory allocation).
The problem might be in the way you call arraycopy(). The destPos is an important offset. If you're copying to that offset, you have to be sure to read from that same offset when you inspect for succesful results. Same goes for offset srcPos.
To troubleshoot, you might inspect results by calling arraycopy() with these offsets set to zero, and check results from the beginning of the destination array. If that worked, then you nailed down the problem area...then look more closely at the handling of your offsets outside of function arraycopy().
EDIT: You asked " guess a better question would be how do I determin the length of a dynamically allocated array because I need to loop through the dynamic array with a for loop, and to do that I need to know the length of the memory allocation"
The length of the array will be whatever you told malloc() to give you, assuming malloc() did not fail:
p = (int*)malloc(50 * sizeof(int));
.... array len is 50....that is, will hold 50 of size int variables.
You might deal with the unknown in code like so:
#define ARRAY_LEN 50
int * some_function(void)
{
int *p;
p = (int*)malloc(ARRAY_LEN * sizeof(int));
return p;
}
void arraycopy(int const * src, int srcPos, int * dest, int destPos, int length){
int i;
int *temp;
if(destPos + length > ARRAY_LEN)
{
puts("too big!!!");
return;
}
temp = (int *)malloc((destPos + length) * sizeof(int));
/// and/or, safe your code like so:
for(i = 0; i < destPos && i < ARRAY_LEN; i++)
{
temp[i] = dest[i];
}
for(i = 0; i < length && i < ARRAY_LEN; i++)
{
temp[i + destPos] = src[i + srcPos];
}
dest = temp;
}
//as you can see, there's a variety of ways to cope with making other functions aware of an externally allocated array length... but determining the length of allocated memory is not provided in standard C. At least as far as I know, 16 yrs experience....