array
- pass array to function
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum=0;
for (i = 0; i < size; ++i){
sum += arr[i];
}
avg = sum / size;
return avg;
}
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
printf( "平均值是: %f ", avg );
return 0;
}
- Function returns an array: returns a pointer to an array
int * getRandom()
{
static int r[10];
int i;
srand((unsigned)time(NULL));
for(i=0;i<10;++i){
r[i] = rand();
}
return r;
}
int main()
{
int *p;
int i;
p=getRandom();
for(i=0;i<10;i++){
printf("*(p+%d):%d\n",i,*(p+i));
}
return 0;
}
- pass pointer to function
void getSeconds(undigned long *par)
{
*par = time(NULL);
return;
}
getSeconds(&sec);
- function returns pointer
int * getRandom()
{
srand((unsigned)time(NULL));
r[3] = rand();
return r;
}
p = getRandom();
printf("%d",*p);
pointer
operator
&
: return variable address
*
: point to a variable
precedence
- NULL: If there is no exact address when declaring a variable, a NULL value can be assigned
int *ptr = NULL;
- Address 0x0, most systems do not allow access to memory at address 0, indicating that it does not point to an accessible memory location.
operation
- increase or decrease
- Increment
ptr++
: Point to the memory location of the next element
- decrement
ptr--
: point to the storage unit of the previous element
- The number of bytes jumped depends on the data type length of the variable pointed to by the pointer (int4 bytes)
- Compare
- ==, <, >
ptr <= &var[MAX-1]
array of pointers
int *ptr[MAX];
ptr[i]=&var;
x=*ptr[i];
const char *names[]={ // 指向字符的指针数组来存储一个字符串列表
"KCZX",
"XHYZ",
"TJDX",
"GKGZ",
};
pointer pointer
int **ptr2;
ptr1 = &V;
ptr2 = &ptr1;
printf("%d",V);
printf("%d",*ptr1);
printf("%d",**ptr2);