C array basic operation and manipulation in comparison to Python

I am switching from Python to C code for the purpose of my project. As I try to manipulate an array, it is very different from what I used to do in python. So I just want to know some "equivalent" operations for an array in C and Python.

So for numpy array in Python, we can directly sum(or other operations) up two arrays elementwise easily. In a sense, I think numpy array is like a virtual "matrix" that you can manipulate with as if it is stored as a whole(at least appear to).

For C array, it looks like a different animal. From what I could search out from the internet, I have to use for loop in order to do these basic operations. I think an array in C is just a set of values that are stored in addresses next to each other in order.

I know that C is much faster than Python, but I also know for loop is a nasty thing that should be avoided as possible in Python. Isn't these for loops in C slow the program down?(though I think when I use numpy module in Python, the module takes care of these for loops implicitly)

I also get a confusion about pointer. Consider this function that takes in a 1D array:

int myfunc(int *myarray);
{
 int sum=0;
 for(int i=0; i<sizeof(myarray); i++)
   {
     sum += myarray[i];
   }
 return sum
 }

Suppose I input some array say "arr", then I let:

*myarray = arr

Thus, later in the function when I am calling lines such as:

sum += myarray[i]

I am actually doing this:

sum += &arr

Which is really confusing. For me, it looks like I am directly adding addresses of variables with values of other variables. Is this code wrong or I misunderstand pointer?

1 answer

  • answered 2017-06-17 19:48 Michaël Roy

    In your function:

    int myfunc(int *myarray);             //  The ; at the end of this line will
                                          //  generate a compiler error.
    {
     int sum=0;
     for(int i=0; i<sizeof(myarray); i++) // size of int* is the size of a pointer
                                          // 4 for 32bit app, or 8 for 64 bits apps
     {
         sum += myarray[i];
     }
     return sum
    }
    

    You should pass the number of elements to your array as a parameter for it to work:

    int myfunc(int *myarray, int count)
    {
     int sum=0;
     for (int i = 0; i < count; i++)                                           
     {
         sum += myarray[i];
     }
     return sum;
    }
    

    [Edit] When you do this:

    sum += &arr;
    

    You are incrementing sum with the address of variable arr.

    Whereas:

    sum += array[i];
    

    increments sum with the int value stored at the (i+1)th position of array.

    The following statement:

    *myarray = arr;
    

    Stores the value of arr into the value pointed to by myarray, this is equivalent to writing:

    myarray[0] = arr;