1
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....

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user2641934
  • 21
  • 1
  • 1
  • 2

4 Answers4

7

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(...
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • in the second one - data being pointed is a string - not the first character. so this is wrong. – Manoj Awasthi Aug 01 '13 at 12:10
  • 1
    Nitpick: As `strlen()` returns `size_t` the suitable conversion specifier should be prefixed by the appropriate length modifier `z` to become `zd`. – alk Aug 01 '13 at 12:11
  • 4
    @ManojAwasthi: `name_pointer` is defined as `char *`, so it points to exactly **one** character. So everything is fine. – alk Aug 01 '13 at 12:16
  • @alk Yes - I concur - thought of that but was uncertain to add that improvement to a basic question. – chux - Reinstate Monica Aug 01 '13 at 12:16
  • 1
    @Manoj Awasthi `record.name_pointer` is a pointer to a `char`, thus the sizeof(*record.name_pointer) will be **1**. As a string in C is a variable length array of characters and the string value is passed about by the address of the first `char`, whether `record.name_pointer` is _used_ to point to only 1 `char`, a string, or a fixed char array is indistinguishable from OP's code snippet. – chux - Reinstate Monica Aug 01 '13 at 12:42
0

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

someone
  • 1,638
  • 3
  • 21
  • 36
0

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

sizeof(char *)
Manoj Awasthi
  • 3,460
  • 2
  • 22
  • 26
  • 9
    Really? I prefer to use the variable, so code usually remains correct if you change the variable type. – sje397 Aug 01 '13 at 12:10
-1

use the following code:

printf("%d\n", (int) sizeof(record->name_pointer)/4);
Hemjal
  • 130
  • 2
  • 7