Reputation: 2011
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
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
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
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 c from an old book probably, be careful!
Upvotes: 1