-1

I have made a function that recieves a pointer of an array of characters, that represent an hexadecimal number, and returns the decimal value of it.

In that function, this is what I currently use to obtain the size of the array

size_t iSize = 0;
while (s[iSize] != '\0'){   iSize++;    }

I am looking to find a better method to do this. I already tried int `iSize = sizeof(s)/sizeof(s[0]).

  • Possible duplicate of [Convert a hexadecimal string to an integer efficiently in C?](http://stackoverflow.com/questions/10324/convert-a-hexadecimal-string-to-an-integer-efficiently-in-c) – hookenz Oct 30 '16 at 19:57
  • 2
    To find the length of a null terminated string use `strlen`. Based on your description that's what you care about, not the size of the array. – Retired Ninja Oct 30 '16 at 19:57
  • 2
    Have you thought about replacing your whole function that converts a hex string to a number with one function `strtol`? – hookenz Oct 30 '16 at 19:58
  • size_t iSize = strlen(s); ? – hookenz Oct 30 '16 at 20:01

1 Answers1

0

Size of array is not passed through a function. Example:

int my_getsize(int* ptr)
{
    return sizeof(ptr);
}

int main()
{
    int arr[100];
    printf("%d\n", sizeof(arr)); //output: 400
    printf("%d\n", my_getsize(arr)); //output: 4
}

In a 32bit system my_getsize(buf) returns 4, which is the size of pointer. While sizeof(buf) returns 400 which is 100 * sizeof(int) (also 4). The only way to around this is to pass the array size to the function. For example foo(arr, sizeof(arr)/sizeof(arr[0]))

Character arrays are a special case because the string is null-terminated, you can look for the last zero in the array. Note however this will not return the array size which includes the null-terminator. It's the same as strlen. Example:

size_t my_strlen(char* ptr)
{
    size_t iSize = 0;
    while (*ptr++) iSize++;
    return iSize;
}

For char buf[] = "12345", sizeof(buf) is 6, while strlen(buf) is 5. Usually you need not worry about optimization with this sort of simple functions because the compiler does it for you.

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77