Home > other >  I have problems with the syntax in C. I'm not so sure about the pointers and the arrays in my p
I have problems with the syntax in C. I'm not so sure about the pointers and the arrays in my p

Time:11-24

This is the program I have written:

#include <stdio.h>

double squareVec(double vec[], int n) {//eckige Klammer
    int j=0;

    for(j=0; j<n;   j) {// Inkrementierung und ; und n ausgebessert und J=0
        double*vec[j] = &vec[j] * &vec[j];
    }

    return vec;
}

int main() {//int main
    double vec[3] = {-1.0,2.0,0.0};
    int j=0;

    squareVec(vec,3);

    for(j=0; j<3;   j) {
        printf("vec[%d] = %f ",j,vec[j]);
    }

    printf("\n");
}

I'm trying this: The function squareVec is to square all entries of a vector. (-1, 2, 0) is to become (1, 4, 0). The vector has to be passed as a pointer.

My problem is:

The line "double*vec[j] = &vec[j] * &vec[j];" is not correct. An array is actually a pointer right, so I don't have to write "

double*vec[j]

double vec[j] ist enough I believe but I'm not sure. Further I believe that the & in "&vec[j]" should also be left out because if I want to have as a result the number squared I don't need to do this by multiplying two adresses, I need to do this with the actual number. I'm also not so sure about the return vec. Do I even need a return function.? Doesn't it automatically go to the main function when the for loop has ended?

I tried exactly this but the compiler always puts out: "squareVec.c:5:1: error: variable-sized object may not be initialized double vec[j]=vec[j]*vec[j];

CodePudding user response:

For starters the return type of the function double and even double * does not make sense. The return type of the function should be void.

There is no sense to declare the variable j outside the for loop and initialize it twice

int j=0;
for(j=0; j<n;   j) {// Inkrementierung und ; und n ausgebessert und J=0

This declaration

double*vec[j] = &vec[j] * &vec[j];

is invalid. And the compiler issues the corresponding error message

squareVec.c:5:1: error: variable-sized object may not be initialized double vec[j]=vec[j]*vec[j];

because it considers this line as a declaration of a variable length array with j elements of the type double *.

Instead you need to write a staement like

vec[j] = vec[j] * vec[j];

Here is your function.

void squareVec( double vec[], size_t n ) 
{
    for ( size_t i = 0; i < n;   i ) 
    {
        vec[i] = vec[i] * vec[i];
    }
}

And the function is called like

double vec[3] = {-1.0,2.0,0.0};
const size_t N = sizeof( vec ) / sizeof( *vec );

squareVec( vec,N );
  • Related