How to make a pointer to a vector? I work on a vector inside the function and I want to keep the values

149 views Asked by At

I am writing a C function so that when called, the function would return an array (vector) of the first p prime numbers(with p given from the keyboard in main).

My problem is when I try to call the function in main.

void vector_prime(int p, int *v[ ],int *total);

This is how my function header looks like, and below is the calling from main.

vector_prime(n,&v,&tot);

Now, the problem is that when I try to give the argument v to the function, v is already a poiner to the first element of the vector, so that trying to write &v is not going to work.

[Error] cannot convert 'int ()[100]' to 'int*' for argument '2' to 'void vector_prime(int, int*, int)'

Here is the error.

Below is the entire code.

If you could help me I would be very grateful.

#include<stdio.h>
#include<stdlib.h>

int prim(int n);
void vector_prime(int p, int *v[],int *total);


int main(void){

    int n,j;
    int v[100], tot;


        puts("Introduceti un numar intreg: ");
        scanf("%d",&n);

        if(prim(n)==1) printf("Numarul %d este prim", n);
                        else printf("Numarul %d nu este prim",n);


        vector_prime(n,&v,&tot);

        for(j=0;  j<tot;   j++) printf("%d ", v[j]);

}



int prim(int n){

    int i,k=0;


    for(i=2;  i<n/2;  i++){
        if(n%i==0)  k++;
    }

    if(k==0) return 1;
        else return 0;


}
//p - primele p numere prime;     
//*v[] - pointer catre vectorul in care va stoca valorile;
///*total - pointer catre locatia la care este stocat numarul de valori prime pana la p;
void vector_prime(int p, int *v[],int *total){

    int i,j=0,d,k;

    for(i=1;   i<p;   i++){
    k=0;
        for(d=2;  d<i/2+1;  d++)

            if(i%d==0) k++;

                if(k==0) {
                    *v[j]=i; (*total)++; j++;
                }

    }
//  for(j=0;  j<*total;  j++) printf("%d  ", *v[j]);


} 

Thanks!!

1

There are 1 answers

0
Some programmer dude On

It's because the second argument of your vector_prime function takes an array of pointers, and you pass it a pointer to an array.

There is no need to pass a pointer to the array here, just pass the array as it is, and modify the vector_prime function accordingly.

So:

void vector_prime(int p, int v[], int *total);

or

void vector_prime(int p, int *v, int *total);

and

vector_prime(n, v, &tot);

You should note that you have some undefined behavior in your code as well: You don't initialize the tot in main, and you don't initialize it in vector_prime either. That means it will contain a seemingly random value to start with.

You should probably check that n is not larger than 100, or smaller than 0. And also note that you don't set v[0] to a value in the vector_prime function.