Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to pass a 2D array as a parameter in C?
Next article icon

Do Not Use sizeof For Array Parameters in C

Last Updated : 01 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers. Consider the below program.  

C




// C Program to demonstrate incorrect usage of sizeof() for
// arrays
#include <stdio.h>
 
void fun(int arr[])
{
    int i;
 
    // sizeof should not be used here to get number
    //  of elements in array
    int arr_size = sizeof(arr) / sizeof(arr[0]);
 
    for (i = 0; i < arr_size; i++) {
        arr[i] = i;
    }
    // executed two times only
}
 
// Driver Code
int main()
{
    int i;
    int arr[4] = { 0, 0, 0, 0 };
    fun(arr);
 
    // use of sizeof is fine here
    for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
        printf(" %d ", arr[i]);
 
    getchar();
    return 0;
}
 
 

Explanation: This code generates an error as the function fun() receives an array parameter ‘arr[]’ and tries to find out the number of elements in arr[] using sizeof operator. 
In C, array parameters are treated as pointers (See this for details). So, the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int) which results in 2 (size of int* is 8 bytes because its an pointer and pointer occupies the 8 bytes of memory and int is 4) and the for loop inside fun() is executed only two times irrespective of the size of the array. Therefore, sizeof should not be used to get a number of elements in such cases. 

Solution: 

1) Using a separate parameter: A separate parameter of datatype size_t for array size or length should be passed to the fun().  size_t is an unsigned integer type of at least 16 bits. So, the corrected program will be:

C




// C Program to demonstrate correct usage of sizeof() for
// arrays
#include <stdio.h>
 
void fun(int arr[], size_t arr_size)
{
    int i;
    for (i = 0; i < arr_size; i++) {
        arr[i] = i;
    }
}
 
// Driver Code
int main()
{
    int i;
    int arr[] = { 0, 0, 0, 0 };
    size_t n = sizeof(arr) / sizeof(arr[0]);
    fun(arr, n);
 
    printf("The size of the array is: %ld", n);
    printf("\nThe elements are:\n");
    for (i = 0; i < n; i++)
        printf(" %d ", arr[i]);
 
    getchar();
    return 0;
}
 
 
Output
The size of the array is: 4 The elements are:  0  1  2  3 

2) Using Macros: We can even define Macros using #define to find the size of arrays, as shown below,

C




// C Program to demonstrate usage of macros to find the size
// of arrays
#include <stdio.h>
 
#define SIZEOF(arr) sizeof(arr) / sizeof(*arr)
 
void fun(int arr[], size_t arr_size)
{
    int i;
    for (i = 0; i < arr_size; i++) {
        arr[i] = i;
    }
}
 
// Driver Code
int main()
{
    int i;
    int arr[] = { 0, 0, 0, 0, 0 };
    size_t n = SIZEOF(arr);
    fun(arr, n);
 
    printf("The size of the array is: %ld", n);
    printf("\nThe elements are:\n");
    for (i = 0; i < n; i++)
        printf(" %d ", arr[i]);
 
    return 0;
}
 
 
Output
The size of the array is: 5 The elements are:  0  1  2  3  4 

3) Using Pointer arithmetic: We can use (&arr)[1] – arr to find the size of the array. Here, arr points to the first element of the array and has the type as int*. And, &arr has the type as int*[n] and points to the entire array. Hence their difference is equivalent to the size of the array.

C




// C Program to demonstrate usage of pointer arithmetic to
// find the size of arrays
#include <stdio.h>
 
void fun(int arr[], size_t arr_size)
{
    int i;
    for (i = 0; i < arr_size; i++) {
        arr[i] = i;
    }
}
 
// Driver Code
int main()
{
    int i;
    int arr[] = { 0, 0, 0, 0, 0 };
    size_t n = (&arr)[1] - arr;
    fun(arr, n);
 
    printf("The size of the array is: %ld", n);
    printf("\nThe elements are:\n");
    for (i = 0; i < n; i++)
        printf(" %d ", arr[i]);
 
    return 0;
}
 
 
Output
The size of the array is: 5 The elements are:  0  1  2  3  4 


Next Article
How to pass a 2D array as a parameter in C?
author
kartik
Improve
Article Tags :
  • C Language
  • C++
  • C Array and String
Practice Tags :
  • CPP

Similar Reads

  • How to print size of array parameter in C++?
    How to compute the size of an array CPP? C/C++ Code // A C++ program to show that it is wrong to  // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize(int arr[]) { cout << sizeof(arr) << endl; } int main() { int a[10]; cout <
    3 min read
  • How to Find Size of an Array in C++ Without Using sizeof() Operator?
    In C++, generally, we use the sizeof() operator to find the size of arrays. But there are also some other ways using which we can find the size of an array. In this article, we will discuss some methods to determine the array size in C++ without using sizeof() operator. Methods to Find the Size of a
    8 min read
  • A shorthand array notation in C for repeated values
    In C, when there are many repeated values, we can use a shorthand array notation to define array. Below program demonstrates same. // C program to demonstrate working of shorthand // array rotation. #include <stdio.h> int main() { // This line is same as // int array[10] = {1, 1, 1, 1, 0, 0, 2
    1 min read
  • Properties of Array in C
    An array in C is a fixed-size homogeneous collection of elements stored at a contiguous memory location. It is a derived data type in C that can store elements of different data types such as int, char, struct, etc. It is one of the most popular data types widely used by programmers to solve differe
    8 min read
  • How to pass a 2D array as a parameter in C?
    A 2D array is essentially an array of arrays, where each element of the main array holds another array. In this article, we will see how to pass a 2D array to a function. The simplest and most common method to pass 2D array to a function is by specifying the parameter as 2D array with row size and c
    3 min read
  • Why Does C Treat Array Parameters as Pointers?
    In C, array parameters are treated as pointers mainly to, To increase the efficiency of codeTo save time It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to cre
    2 min read
  • array::max_size() in C++ STL
    Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::max_size() This function returns the maximum number of elements that the array container can contain. In c
    1 min read
  • sizeof operator in C
    Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as integ
    3 min read
  • How to Take Input in Array in C++?
    Arrays in C++ are derived data types that can contain multiple elements of the same data type. They are generally used when we want to store multiple elements of a particular data type under the same name. We can access different array elements using their index as they are stored sequentially in th
    3 min read
  • array::size() in C++ STL
    The array::size() method is used to find the number of elements in the array container. It is the member method std::array class defined inside <array> header file. In this article, we will learn about the array::size() method in C++. Example: [GFGTABS] C++ // C++ Program to illustrate the use
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences