Thread: Getting array size

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    13

    Question Getting array size

    Code:
    #pragma once
    #define SIZE(a) sizeof(a) / sizeof(a[0])
    
    
    #include <stdio.h>
    
    
    void iter_ints (int arr[])
    {   
        int arrSize = SIZE(arr);
        printf("arrSize %i\n", arrSize);
    }
    The warning says "warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int *", but using "int *arr[]" is not working also so idk how to solve this basic issue here.

    I see lots of ppl are using sizeof(a) / sizeof(a[0]) to get array sizes but it doesn't seem to work for me.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The simple solution is to provide a second parameter for the array size:
    Code:
    void iter_ints(int arr[], size_t arrSize)
    {
        printf("arrSize %zu\n", arrSize);
        // ...
    }
    I have chosen size_t as the type of arrSize because that is the type of the result of sizeof. Likewise, the format specifier for printf was changed to %zu as that is the format specifier for size_t. If your compiler complains about this, then change %zu to %lu and cast arrSize to unsigned long.

    You might call this function like this:
    Code:
    int numbers[] = {2, 3, 5, 7, 11};
    iter_ints(numbers, sizeof(numbers) / sizeof(numbers[0]));
    In this context, the sizeof division method works fine because numbers really is an array, not a pointer. In iter_ints, the sizeof division method does not give you the size of the array because arr is actually a pointer, hence we pass the array size as an argument.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 10-20-2019, 02:00 PM
  2. Declare 2D array without size, give size later
    By ColeBacha in forum C Programming
    Replies: 4
    Last Post: 04-18-2019, 11:50 PM
  3. size of an array poited by array element
    By mitofik in forum C Programming
    Replies: 7
    Last Post: 12-24-2010, 12:09 AM
  4. size of array - why function gives size ONE only
    By noob123 in forum C++ Programming
    Replies: 7
    Last Post: 12-18-2009, 05:20 PM
  5. Finding Words in a array[size][size]
    By ^DJ_Link^ in forum C Programming
    Replies: 8
    Last Post: 03-08-2006, 03:51 PM

Tags for this Thread