CLover
CLover

Reputation: 23

Squaring Each element with pointers (C)

I am trying to write a C program that squares each element of an array:

Input:

 v = {1,2,3}

Output:

 v = {1,4,9}

Here is my C code:

 #include <stdio.h>
 #include <math.h>


 void squaredVector(int *rowVector[] , int arrayLength);

 int main(void)
 {
    int result;
    int a[] = {1 , 2 , 3};
    result = squaredVector(&a , 3); /* use the address of array a */
    printf("%d" , result);
    return 0;
 }

The function that squares my vector:

 void squaredVector(int *rowVector[] , int arrayLength) 
 {
   int i;
   for(i = 0; i < arrayLength; i++)
   {
      *rowVector[i] = (*rowVector[i]) * (*rowVector[i]);
   }
}

I am not really sure what the function is doing, but I assume the values of the array are being passed to the square vector function. I assume that:

 *rowVector[i] = (*rowVector[i]) * (*rowVector[i]);

is taking element a[i] and squaring it using unmasked pointers

Upvotes: 0

Views: 2451

Answers (1)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

You are using a 1D array, so you should not use

void squaredVector(int *rowVector[] , int arrayLength);  // This is an array of pointers

Instead the proper function declaration is

void squaredVector(int rowVector[] , int arrayLength);   //1D array

OR

void squaredVector(int *rowVector , int arrayLength);   //1D array

Inside the function, the for loop should change to

for(i = 0; i < arrayLength; i++)
{
    rowVector[i] = (rowVector[i]) * (rowVector[i]);
}

Call the function in main by

result = squaredVector(a , 3);  

Upvotes: 1

Related Questions