asad_hussain
asad_hussain

Reputation: 2011

Why is the output of this code is 4?

I am using sizeof function to calculate the size of a string. It should have printed 2.But why 4? Here is the code.

#include <stdio.h>
#include <string.h>

void main()
{       
    char *b = "ab";

    printf(" %d ",sizeof(b));
   //printf("%s ",b);
}

Upvotes: 0

Views: 52

Answers (3)

Magisch
Magisch

Reputation: 7352

char *b = "ab";

In your case, b is a pointer to a read-only string literal in the file. Pointers in your case have a size of 4 in your system.

If you want to find out lenght, you can use strlen() to do so.

Sizeof returns the size of the variable you pass to it in bytes.

Fun fact: You can even print the pointer!

printf("%p\n",b);

An example for an output would be:

0x8048555

Upvotes: 1

user3386109
user3386109

Reputation: 34839

sizeof is a keyword, not a function, and it tells you the size of a variable in bytes. The variable b is a pointer, and its size (on your system) is 4 bytes. If you want the length of a string, use the strlen function.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Because on your platform pointers are 4 bytes. Or 32bit if you prefer.

NOTE: Using void main() as a signature for main() indicates that you are studying from an old book probably, be careful!

Upvotes: 1

Related Questions