0

Firstly before I explain, here is the code in C:

#include <stdio.h>

void printSize(char* str);

int main()
{
    char a[100] = "StackOverflow";
    printSize(a);
    return 0;
}

void printSize(char* str)
{
    int n = sizeof(str) / sizeof(char);
    printf("%d" ,n);
}

As you can already see, I am trying to get my function to print the value "100" as 100 is the size that I have allocated to my char array a. However I am getting 8 as my answer. Now I know why I am getting 8 here because it's printing the size of the pointer. So my question is, if I can't use this method to print out the value of "100" then how can I find out the memory allocated to a from inside the function?

Thanks

theprogrammer
  • 1,698
  • 7
  • 28
  • 48

1 Answers1

3

To get the length of a string you use the strlen function. To get the size of the array you need to pass it as an argument.

When you get the size of a pointer, you get the size of the actual pointer and not what it points to. In your case you seem to be on a 64-bit platform where pointers are 64 bits (8 bytes), then dividing that by sizeof(char) (which is defined to always be 1) you get the value 8.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621