how to find length of an unsigned char pointer in C?

QtUser picture QtUser · Apr 3, 2014 · Viewed 20.9k times · Source

I want to find size or length of an unsigned char pointer in a function where that pointer is an argument to that function.Near the pointers declaration size is coming correctly.

But when i am trying to find size in function it is giving 4.

How can i do this ?

#include <stdio.h>
//void writeFile(unsigned char *da);
void writeFile(char *da);
int main(int arc,char **argv)
{

 unsigned char block_bmp[]=
{
   0x0,0xff,0xff,0xff,0x0,0x0,0x0,0xff,0xff,0xff,0x0,0x0,0x0,0xff,0xff,0xff,//*16bytes*
};
printf("size::%d\n",sizeof(block_bmp));
writeFile(block_bmp);
}

//void writeFile(unsigned char *da)
void writeFile(char *da)
{
printf("%d\n",__LINE__);
printf("size::%d\n",sizeof(da));
printf("length::%d\n",strlen(da));
FILE *fp;
int i;
fp=fopen("/tmp/hexfile","wb");
for(i=0;i<3780;i++)
    fprintf(fp,"%c",da[i]); 
//  fwrite(da,sizeof(unsigned char),sizeof(da),fp);
fclose(fp);
}

Answer

Callidior picture Callidior · Apr 3, 2014

If it points to a NULL-terminated string, use strlen. If not, the pointer is just some memory address for the called function, without any additional information about the size of the array (I assume, you try to pass an array). I suggest passing the number of array elements as additional parameter to the function.