-1

I tried to get how many bytes are allocated for an array using standalone function but I failed. My code is as follows:

#include <stdio.h>

void testing(char *source);

int main(){

    char a[12] = "Hello World!";
    //printf("%d",sizeof(a));   Prints 12. I want to get this value
    testing(a); // Prints 4. I need to get 12 by using functions


return 0;
}

void testing(char *source){
    printf("%d",sizeof(source));
}

I want to get result as 12 but output tells me that it is 4.

Abdulla
  • 41
  • 6
  • You can't get the size of an array from `sizeof` with a pointer. – Eli Sadoff Jan 13 '17 at 01:15
  • It is like saying "I want 2+2 to be 5". You can keep to "want" it, but it won't happen. `sizeof` does not do this. – AnT Jan 13 '17 at 01:23
  • change function to `void testing( char (*source)[12] )` and then in function use `sizeof *source` – M.M Jan 13 '17 at 01:24

1 Answers1

0

I want to get result as 12 but output tells me that it is 4.

You can't get the size of an array when it's passed as pointer to function.

In void testing(char *source), source is pointer, so sizeof( pointer ) gives you 4 (4 bytes in your machine).

There is no way to find out the array size inside the function, as array parameter will decay to pointer anyway.

artm
  • 16,750
  • 4
  • 31
  • 51