c

Why does my C program give an error when looping through an array?


When I try to run the following C code, it does not work as expected. I am trying to shift the elements of the array to the left, but I get errors. What is wrong with my code?

#include <stdio.h>

int main()
{
    int arr[] = {1,5,7,10};
    
    for (int i = 0; i < arr; i++)
    {
        arr[i] = arr[i+1];
    }
    
    for (int i = 0; i < arr; i++)
    {
        printf("Arr[%d] = %d\n", i, arr[i]);
    }
    
    return 0;
}
   

I tried to take the size of the array in the first loop but that didn't solve the problem.

Issues I noticed:

I am unsure how to properly loop through the array. The loop condition i < arr does not seem correct. Is my array modification (arr[i] = arr[i+1];) valid?

Could someone help me understand why this doesn't work and how to fix it?


Solution

  • i < arr is a comparison between an integer and a pointer, that means nothing to what you initially intended. i < arr is also a constraint violation and invalid C (6.5.9).

    You may want to traverse through the array till the last element.

    sizeof is the operator you need.

    1. sizeof(arr), gives the combined size of the whole array resulting in 16 bytes on a x86_64 architecture.
    2. sizeof(arr) / sizeof(arr[0]), gives size of each element as sizeof(arr[0]) results in 4 bytes on a x86_64 architecture.

    So, your for should look like this:

    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
    {
        // code
    }