user2641934
user2641934

Reputation: 21

Size of pointer variable in a structure

int main()
{
    struct
    {
        char *name_pointer;
        char all[13];
        int foo;
    } record;

    printf("%d\n",sizeof(record.all));
    printf("%d\n",sizeof(record.foo));
    printf("%d\n",sizeof(record));

    return 0;
}

I want the size of the pointer vatiable "*name_pointer" in the structure....

Upvotes: 1

Views: 12908

Answers (4)

Hemjal
Hemjal

Reputation: 310

use the following code:

printf("%d\n", (int) sizeof(record->name_pointer)/4);

Upvotes: -1

chux
chux

Reputation: 154262

To get the size of the pointer use

printf("%d\n", (int) sizeof(record.name_pointer));

Your might get 2, 4, 6, 8, etc.


To get the size of the data that is pointed to by the pointer (a char) use

printf("%d\n", (int) sizeof(*record.name_pointer));

Your should get 1.


To get the string length of the string pointed to by the pointer, assuming record.name_pointer points to legitimate data, use

printf("%d\n", (int) strlen(record.name_pointer));

BTW As @alk says and why the (int) casting above, a suitable conversion specifier to use with sizeof() includes the 'z' prefix. The result of sizeof() and strlen() is of type size_t. Although size_t and int are often the same, there are many systems where they are of different sizes. And since sizeof() is an "unsigned integer type" (C11 6.5.3.4), I recommend

printf("%zu\n", sizeof(...

Upvotes: 7

Manoj Awasthi
Manoj Awasthi

Reputation: 3520

I believe it is a GOOD idea to use data types in sizeof rather than variables for native data types. so use:

sizeof(char *)

Upvotes: 0

someone
someone

Reputation: 1694

Pointer variable will always(32 bit system architecture) have size 4. if you have 64 bit system architecture it is 8.

Upvotes: 0

Related Questions