Thread: sizeof function confusion

  1. #1
    Registered User
    Join Date
    Jan 2017
    Posts
    9

    sizeof function confusion

    Hello,

    i learning to code without any prior experience to it whatsoever. Here is my confusion regarding the function sizeof().

    So, when declaring an array, the name of array is just a pointer to its first element. Then, why is the output in the following code is 12 and not 4, which is the actual size of the variable "movie1"?

    Code:
    int main()
    {
        char movie1[] = "Hello World";
    
    
        printf("%d", sizeof(movie1));
    
    
        return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    A couple of things.

    Despite the function-like syntax, sizeof is an operator (like + or -), not a function.
    The parentheses are only required when referring to types.

    Eg.
    Code:
    #include<stdio.h>
    int main() {
      char movie1[] = "Hello World";
      printf("%zd\n", sizeof movie1);
      return 0;
    }
    > So, when declaring an array, the name of array is just a pointer to its first element
    Not quite.
    The name of the array is the name of the array.
    The "array becomes a pointer to the first element" happens in most circumstances, but not all.
    One example as you have found is when using an array name in a sizeof expression.
    Arrays and Pointers
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jan 2017
    Posts
    9
    Thank You, Salem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sizeof from a second function
    By ShungTzu in forum C Programming
    Replies: 8
    Last Post: 04-21-2016, 10:49 PM
  2. sizeof inside function
    By haecifer in forum C Programming
    Replies: 1
    Last Post: 07-16-2015, 04:29 AM
  3. sizeof function and pointers
    By johnmerlino in forum C Programming
    Replies: 2
    Last Post: 04-07-2014, 05:03 AM
  4. sizeof function
    By chrismiceli in forum C Programming
    Replies: 10
    Last Post: 02-28-2004, 08:28 PM
  5. SizeOf function
    By vanilly in forum C Programming
    Replies: 4
    Last Post: 02-13-2003, 12:18 PM

Tags for this Thread