Thread: Declaring an array in C without giving size

  1. #1
    Registered User
    Join Date
    Jun 2009
    Location
    Bangalore,India
    Posts
    29

    Declaring an array in C without giving size

    Code:
    int main() {
        int arr[] = {1, 2, 3, 4, 5};
    }
    Here we do not give array size. So how memory (20 bytes) allocated for arr?
    By counting the numbers between comma(,) operators inside the curly braces?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    Yes, the compiler counts the initialisers, and allocates the array size based on that count.
    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 Sir Galahad's Avatar
    Join Date
    Nov 2016
    Location
    The Round Table
    Posts
    277
    Quote Originally Posted by krishnampkkm View Post
    Code:
    int main() {
        int arr[] = {1, 2, 3, 4, 5};
    }
    Here we do not give array size. So how memory (20 bytes) allocated for arr?
    By counting the numbers between comma(,) operators inside the curly braces?
    The general rule for arrays: all but the first dimension must be explicitly sized.

    Code:
    int a1[][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};    // fine
    Code:
    int a2[][][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};    // error!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 05-11-2013, 02:43 PM
  2. Problem in declaring array size inside a function
    By dpitz in forum C Programming
    Replies: 14
    Last Post: 04-27-2012, 04:17 PM
  3. Declaring an object of class type. Giving errors, need help!
    By Kristyy_mariee in forum C++ Programming
    Replies: 8
    Last Post: 03-01-2012, 11:51 AM
  4. help with declaring array in which the user specifies size
    By ibanezrgking in forum C++ Programming
    Replies: 3
    Last Post: 02-10-2002, 10:05 AM
  5. Declaring int of specific bit size
    By Natase in forum C Programming
    Replies: 6
    Last Post: 08-26-2001, 09:22 PM

Tags for this Thread