指针用于存储动态分配的数组的地址以及作为参数传递给函数的数组。在其他情况下,数组和指针是两个不同的东西,请参阅以下程序来证明此声明的合理性。
sizeof 运算符的行为
sizeof 运算符的行为
// 1st program to show that array and pointers are different
#include <stdio.h>
int main()
{
int arr[] = { 10, 20, 30, 40, 50, 60 };
int* ptr = arr;
// sizof(int) * (number of element in arr[]) is printed
printf("Size of arr[] %ld\n", sizeof(arr));
// sizeof a pointer is printed which is same for all
// type of pointers (char *, void *, etc)
printf("Size of ptr %ld", sizeof(ptr));
return 0;
}
输出
Size of arr[] 24 Size of ptr 8
不允许将任何地址分配给数组变量。
// IInd program to show that array and pointers are different
#include <stdio.h>
int main()
{
int arr[] = {10, 20}, x = 10;
int *ptr = &x; // This is fine
arr = &x; // Compiler Error
return 0;
}
输出:
Compiler Error: incompatible types when assigning to type 'int[2]' from type 'int *'
尽管数组和指针是不同的东西,但数组的以下属性使它们看起来相似。
- 数组名称给出数组第一个元素的地址。
例如,考虑以下程序。
#include <stdio.h>
int main()
{
int arr[] = { 10, 20, 30, 40, 50, 60 };
// Assigns address of array to ptr
int* ptr = arr;
printf("Value of first element is %d", *ptr);
return 0;
}
输出
Value of first element is 10
使用指针算法访问数组成员。
编译器使用指针算法来访问数组元素。例如,像“arr[i]”这样的表达式被编译器视为*(arr + i)。这就是为什么像 *(arr + i) 这样的表达式适用于数组 arr,而像 ptr[i] 这样的表达式也适用于指针 ptr。
编译器使用指针算法来访问数组元素。例如,像“arr[i]”这样的表达式被编译器视为*(arr + i)。这就是为什么像 *(arr + i) 这样的表达式适用于数组 arr,而像 ptr[i] 这样的表达式也适用于指针 ptr。
#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int *ptr = arr;
printf("arr[2] = %d\n", arr[2]);
printf("*(arr + 2) = %d\n", *(arr + 2));
printf("ptr[2] = %d\n", ptr[2]);
printf("*(ptr + 2) = %d\n", *(ptr + 2));
return 0;
}
输出
arr[2] = 30 *(arr + 2) = 30 ptr[2] = 30 *(ptr + 2) = 30
数组参数总是作为指针传递,即使我们使用方括号。
#include <stdio.h>
int fun(int ptr[])
{
int x = 10;
// size of a pointer is printed
printf("sizeof(ptr) = %d\n", (int)sizeof(*ptr));
// This allowed because ptr is a pointer, not array
ptr = &x;
printf("*ptr = %d ", *ptr);
return 0;
}
// Driver code
int main()
{
int arr[] = { 10, 20, 30, 40, 50, 60 };
// size of a array is printed
printf("sizeof(arr) = %d\n", (int)sizeof(arr));
fun(arr);
return 0;
}
输出
sizeof(arr) = 24 sizeof(ptr) = 4 *ptr = 10