1.

int a = 1025;
int *p;
p = &a;
printf("size of integer is %d bytes\n".sizeof(int));
printf("Address = %d, value = %d\n",p,*p);
char *p0;
p0 = (char*)p;
printf("size of char is %d bytes\n".sizeof(char));
printf("Address = %d, value = %d\n",p0,*p0);
Copy the code

The result of the above code is

The problemP0 and p point to the same address, but fetch different values.answer: The binary representation of 1025 is 00000000 00000000 00000100 00000001. P0 is a pointer to the char type and contains only one byte. Therefore, the value can be set to only one byte of the lower address, that is, 00000001 is 1.

2.

#include <stdio.h>
int SumOfElements(int A[]) // this is interpreted by the compiler as int *A
{
    int i, sum = 0;
    int size = sizeof(A) / sizeof(A[0]);
    printf("SOE - Size of A = %d, size of A[0] = %d\n".sizeof(A),sizeof(A[0]));
    for(i = 0; i < size; i++) { sum += A[i]; }return sum;
}

int main(a)
{
    int A[] = {1.2.3.4.5};
    int total = SumOfElements(A);
    printf("Sum of elements = %d\n",total);
    printf("Main - Size of A = %d, size of A[0] = %d\n".sizeof(A),sizeof(A[0]));
}
Copy the code

The result of the above code is



The problemWhy is array A of different sizes in main and SumOfElement?

answerSumOfElement: A is an argument to SumOfElement, where A is A pointer to the address. So, sizoef(A) results in the size of the pointer variable A in memory, typically 4 bytes on A 32-bit machine. To get the size of an array for a function, there are two ways:

  1. Write a fixed array size in the function code
int SumOfElements(int A[]) 
{
    int i, sum = 0;
    int size = sizeof(A) / sizeof(A[0]);
    printf("SOE - Size of A = %d, size of A[0] = %d\n".sizeof(A),sizeof(A[0]));
    for(i = 0; i <10; i++) { sum += A[i]; }return sum;
}
Copy the code
  1. Take the array size as the second argument to the function.