김현영 김현영 - 1 month ago 19
C Question

C lang sizeof(char[]) get static size

I want to get char array size but I cant do that

let see

#define MAX 64

char value[MAX]

value = "hi" //or something initialization
sizeof("hi") //result = 3
sizeof(value) // result = 64


I want to get
sizeof("hi") == sizeof(value)

How cant I do?

Answer

In the snippet that you've included, you're actually setting the size of value to 64. As a result sizeof(value) will return 64 * sizeof(char). This is correct, regardless of what you're putting into the array value.

Perhaps what you're trying to do is to get the array to be automatically sized at compile time? e.g.

char value[] = "hi";
int value_size = sizeof(value); // value_size will now equal 3, as the array contains { 'h', 'i', '\0' }