march_seven march_seven - 1 month ago 8
C Question

how does the C pointer could being as the formal parameter of function like this?

there is a sample in the chapter pointer of C Primer Plus Book.

I am so confuse about the code which set the array name into the sump function as formal parameter

Answer = sump(array, array + SIZE);

start is 00EFFBD8 ,it is ok that means arrary[0] address
but when it action : int *end = array +SIZE // =>" array[0] address + 10"

why end is 00EFFC00 (00EFFBD8 + 10*4), why not 00EFFBD8 +10 ???

enter image description here

#include <stdio.h>

#array size
#define SIZE 10

#sum function
int sump(int *start, int *end);

int main(void)
{
int array[SIZE] = { 10,9,8,7,6,5,4,3,2,1 };
long Answer;

Answer = sump(array, array + SIZE);
printf("a is %d\n", Answer);

return 0;
}

int sump(int *start, int *end)
{
int total=0;

while (start < end)
{
printf("start is %p, %d\n", start, *start);
printf("end is %p, %d\n", end, *end);
total += *start++;
}

return total;
}

Answer Source

Well, each and every data-type int float long and so on.. each occupy some space in the memory when you declare them. For example:

int k; //occupies 4-bytes of memory
float f; //occupies 4-bytes of memory
long l; //occupies 8-bytes
char c; //occupies 2-bytes

That's the C's convention for allocating memory to the variables. Now when you talk about addresses. Imagine memory is in form of blocks and base address/start address is 100. So when you declare an int type variable, it will place it at 100. But, int needs 4-bytes of memory so, the blocks that the CPU will give to this variable 'k' are, 100, 101, 102 and 103 (considering all these blocks are size 1-byte each). So now blocks 100 to 103 are allocated for variable-k.

When you declare an array of int type: int arr[10], the CPU makes 10 such k-variable that i made up there. So that means:

arr[0] //this will have address from 100 to 103
arr[1] //will have address from 104 to 107
arr[2] //will have address from 108 to 111

and so on, while the base address, that is the address of the whole array arr is 100. So you can calculate the address of arr[1] as base address of array + index*size of int where we know that base address of array is 100, index is what we need to calculate (that is 1) and size of int as i said earlier is 4-bytes. So, address of arr[1] = 100 + 1*4 = 104.

Similarly, the end address, that is the arr[9], will be 100 + 9*4 = 136 and the array will end at, 100 + 10*4. Now in your question the values are hexadecimals and base address is not hundred.