0
char* username

is a pointer to the beginning of a character array (in c).

How do I calculate the size of the array, is there is function that can do it?

spatara
  • 893
  • 4
  • 15
  • 28
  • 7
    if it is null terminated, use `strlen` – perreal Mar 14 '12 at 18:37
  • As perreal said, if it is NUL terminated, use strlen. If it is allocated using malloc, you may be able to use some non-standard way to look in the malloc system's internal data. Otherwise, you're probably out of luck. – Thomas Padron-McCarthy Mar 14 '12 at 18:40

3 Answers3

2

use strlen(username). But the array has to terminated by '\0'. Otherwise you cannot do that.

anirudh
  • 562
  • 6
  • 23
  • That doesn't give the size of the array; that gives the length of the null-terminated string IN the array. IF you trust the array to be at least as large as the string is long (+ '\0') then you can get a minimum length of the array, but that's all. – Technophile Sep 21 '22 at 03:53
1

You can't do that. If this is an array you allocated, you should have the size of it to start with. For what C and the compiler know, this is just a pointer.

MByD
  • 135,866
  • 28
  • 264
  • 277
-1

If this is a null-terminated string, use strlen to count it's non-null characters, then the array length is at least length + 1 characters.

If you have the array base pointer, you could use sizeof(pointer) to get the size allocated to it by the memory manager.

Spidey
  • 2,508
  • 2
  • 28
  • 38
  • 2
    That's not how `sizeof` works. `sizeof` returns the size of the pointer itself. – Fred Foo Mar 14 '12 at 18:43
  • You are correct, you could use sizeof for arrays though. Like char my_string[500]; and then sizeof(my_string) will return 500. But since the OP conext is inside a function, that won't work. – Spidey Mar 14 '12 at 18:51