Pointer algebra: pointer to an array

Hi,

I always get confused with pointer to an array. So, I made some examples showing my confusion. I would appreciate if someone could answer those.

I have marked "main" code in part-1 to part-3 and I have question from those parts.

In part 1 & definition of function "func":
Q.1) function template is: int func(int* , int* ). How come it accepts func(B, pmult); in part-1 where first argument is an array rather than a pointer.

Q.2) Inside the function, Why can not I write:
*B[4] = 5;
Or why does this works
B[4] = 5;

Part 2:
Q.3) Just ensuring that I understand it correctly. I can not find the size of array if I have access to its pointer. In other words, I can not find the size of array B from inside function "func", Am I right?


Part 3:
Q.4) Why can not I write this
int * p = &numbers; *p = 10; // This does not work
Or, why this works?
int * p = numbers; *p = 10;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include "stdafx.h"
#include <iostream>     // std::cout, std::endl

int func(int *B, int* pmult){
	B[4] = 5;  //Why can not I write: *B[4] = 5;
	*(B+3) = 10;
	return 0;
}

int main(void){

	//Part-1
    int B[6] = {1, 2, 3, 4, 5, 6};
	int mult = 5;
	int* pmult = &mult;
    func(B, pmult);

	for (int n=0; n<6; n++)
		std::cout << B[n] << ", ";

	// Part-2: Finding the size of an array
	int Size_sz = sizeof(B)/sizeof(B[0]);  // Calculating the size of the array
	std::cout << " Size_sz  " << *pmult << "\n";

	// Part-3: Understanding some pointer algebra
	  int numbers[5];
	  //int * p = &numbers;  *p = 10;	// This does not work
	  int * p = numbers;    *p = 10;		
	  p++;  *p = 20;				
	  p = &numbers[2];  *p = 30;	
	  p = numbers + 3;  *p = 40;	
	  p = numbers;  *(p+4) = 50;	
	  for (int n=0; n<5; n++)
		std::cout << numbers[n] << ", ";

    return 0;
}
Last edited on
Q1) Arrays can be implicitely converted to pointers to its first element

Q2) B[4] is equivalent to *(B + 4): advance pointer 4 spaces forward and dereference it. Result of B[4] is lvalue of type int. As you cannot dereference int, you cannot do *B[4]

Q3) Yes, converting array to pointer will erase all information of its type and attempt to calculate size of array will come out terribly wrong. That is why this method of array size calculation is not recommended in C++ as unsafe.

Q4) Because array has its own type: int[5] in your case, so its address is of type int(*)[5], which cannot be converted to simple int pointer. (And even if it was allowed, you will have an address of array, so it would have to be at least double pointer). You have to rely on implicit conversion of array to pointer.
Thanks, MiiNiPaa.
Topic archived. No new replies allowed.