Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different answers from strlen and sizeof for Pointer & Array based init of String [duplicate]

Tags:

c++

c

Possible Duplicates:
C: differences between pointer and array
Different sizeof results

Basically, I did this...

 char *str1 = "Sanjeev";
 char str2[] = "Sanjeev";
 printf("%d %d\n",strlen(str1),sizeof(str1));    
 printf("%d %d\n",strlen(str2),sizeof(str2));

and my output was

7 4
7 8

I'm not able to give reasons as to why the sizeof str1 is 4. Please explain the difference between these.

like image 571
1s2a3n4j5e6e7v Avatar asked May 08 '11 06:05

1s2a3n4j5e6e7v


People also ask

What is the difference between strlen and sizeof?

sizeof() vs strlen() vs size() Data Types Supported: sizeof() gives the actual size of any type of data (allocated) in bytes (including the null values), strlen() is used to get the length of an array of chars/string whereas size() returns the number of the characters in the string.

Can you use strlen on a pointer?

strlen() accepts a pointer to an array as argument and walks through memory at run time from the address we give it looking for a NULL character and counts up how many memory locations it passed before it finds one.

Does sizeof work on pointers?

In other words, sizeof() works the same way for pointers as for standard variables. You just need to take into account the target platform when using pointers.

Should I use sizeof or strlen?

strlen() is used to get the length of a string stored in an array. sizeof() is used to get the actual size of any type of data in bytes. Besides, sizeof() is a compile-time expression giving you the size of a type or a variable's type. It doesn't care about the value of the variable.


2 Answers

Because sizeof gives you the size in bytes of the data type. The data type of str1 is char* which 4 bytes. In contrast, strlen gives you the length of the string in chars not including the null terminator, thus 7. The sizeof str2 is char array of 8 bytes, which is the number of chars including the null terminator.

See this entry from the C-FAQ: http://c-faq.com/~scs/cclass/krnotes/sx9d.html

Try this:

 char str2[8];
 strncpy(str2, "Sanjeev", 7);
 char *str1 = str2;
 printf("%d %d\n",strlen(str1),sizeof(str1));    
 printf("%d %d\n",strlen(str2),sizeof(str2));
like image 102
Robert S. Barnes Avatar answered Sep 28 '22 18:09

Robert S. Barnes


str1 is a pointer to char and size of a pointer variable on your system is 4.
str2 is a array of char on stack, which stores 8 characters, "s","a","n","j","e","e","v","\0" so its size is 8

Important to note that size of pointer to various data type will be same, because they are pointing to different data types but they occupy only size of pointer on that system.

like image 30
Alok Save Avatar answered Sep 28 '22 18:09

Alok Save