1
#include<stdio.h>

void printS(char []);

int main(){
    char str[]="The C Programming Language"; 
    printf("%d \n",sizeof(str)); //output=27
    printS(str);
}

void printS(char s[]){
    printf("%d \n",sizeof(s)); //output=4
}

Why this anamolous output

please explain what is the difference between 'str' and 's'.... and how can i have sizeof() output=27 in printS function.

Shashank Singh
  • 81
  • 1
  • 1
  • 5
  • 1
    In intro classes, we are often taught that arrays are pointers, and pointers are arrays. This is **not** true. They are similar in many ways, but not the same. – abelenky Sep 26 '13 at 17:12

3 Answers3

4

When you pass an array to a function like you are it will decay to a pointer and therefore sizeof will be returning the size of a pointer not the size of the array. The C Faq's section on Arrays and Pointers is a great reference and Question 6.4 covers this exact issue. The relevant section of the C99 draft standard is section 6.3.2.1 Lvalues, arrays, and function designators paragraph 3 which says(emphasis mine):

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

In order to obtain the length of a C style string you can use strlen from string.h header file.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
3

The value of sizeof() is the size of one variable of the specified type. s is actually char*, so sizeof(s) is 4 (on your 32-bit platform). In main(), str is treated as an array of char, so sizeof(str) is the size of the array. Note that the length of "The C Programming Language" is 26, the extra one byte is for the zero terminator.

To get the length of s, use strlen(s). This time the zero terminator is not counted. And don't forget to #include <string.h> at the beginning.

Chen
  • 1,170
  • 7
  • 12
0

C does not have the feature of passing array values. Arrays are always passed as pointers, when you declare a parameter of type foo[] you are effectively declaring foo *.

bmargulies
  • 97,814
  • 39
  • 186
  • 310