problem step of arrays as pointers

1

I was doing a program to calculate the central element of a vector, as parameters I have to pass the base direction of a vector (that is, the pointer is already by default points to the first element) and the number of elements, my main The question is, what is the difference between doing p = &vector; and doing only p=vector .

This is the program:

#include<iostream>

using namespace std;
int elemento_central (int *array, int elementos );


int main (void){
  int vector[10];
  int central =0;
  int *p;

  vector[0]=50;
  //p = vector;

  p = &vector;
  for (int i=1; i <= 10;i++){
    vector[i]=vector[i-1]+1;
    //(*vector[i])++;
  }


  int b= elemento_central (vector,10);

   cout << " el elemento central es " << central << endl; 

}  

int elemento_central (int *array, int elementos) {
  int izq;

  *array=izq;

  int dch;

  *array + (elementos-1) = dch;

  int mitad = (izq + dch)/2;

  return mitad;
}

I corrected a couple of errors when compiling it, but I did not want to do the program without having some concepts clear.

and I still get this error in the compiler:

pseudocodigop6.cpp: In function ‘int elemento_central(int*, int)’:
pseudocodigop6.cpp:36:26: error: lvalue required as left operand of assignment
   *array + (elementos-1) = dch;
    
asked by AER 08.05.2017 в 13:57
source

1 answer

3

The declaration of the vector:

int vector[10];

is, in terms of pointers, equivalent to this one:

int* vector;

That is, the variable vector is really a pointer that points to the first position of the array. Thus, vector[4] is equivalent to vector + 4 , that is, it applies a displacement of 4 positions on the position pointed to by vector (and that is why you thus access the 5th element).

On the other hand, the reference allows you to obtain the memory position where a variable is found:

int var;
int* ptr = &var;   // ptr almacena la posición de memoria de var
int** ptr2 = &ptr; // ptr2 almacena la posición de memoria de ptr

So, if you do p = &vector then p should be a double pointer, which is not the case and therefore that instruction is wrong. The correct thing is to do p = vector

    
answered by 08.05.2017 в 14:33