由于我只是个学习者,所以我对上面的问题感到困惑。指向数组的指针与指针数组有何不同?请向我解释,因为我将不得不解释给我的老师。谢谢。
发布于 2013-11-21 11:48:49
背景
将指针看作是一个单独的数据类型。它们有自己的存储需求--比如它们的大小--它们在x86_64平台上占用8个字节。这是无效指针void*的情况。
在这8个字节中,存储的信息是另一个数据的内存地址。
关于指针的问题是,由于它们“指向”了另一段数据,所以知道数据的类型也很有用,这样您就可以正确地处理它(知道它的大小和结构)。
与其拥有自己的数据类型名称(如pointer ),不如根据所引用的数据类型(如指向整数的指针int* )组合它们的名称。如果您想要一个没有附加类型信息的普通指针,您可以选择使用void*。
因此,基本上每个指针(指向int、char、double)都只是一个void* (相同大小、相同用途),但是编译器知道所指向的数据是int类型,并允许您相应地处理它。
/**
* Create a new pointer to an unknown type.
*/
void* data;
/**
* Allocate some memory for it using malloc
* and tell your pointer to point to this new
* memory address (because malloc returns void*).
* I've allocated 8 bytes (char is one byte).
*/
data = malloc(sizeof(char)*8);
/**
* Use the pointer as a double by casting it
* and passing it to functions.
*/
double* p = (double* )data;
p = 20.5;
pow((double* )data, 2);指向数组的指针
如果在内存中有一个值数组(例如整数),则指向它的指针是一个包含其地址的变量。
您可以首先取消指针的引用,然后对数组及其值进行操作,从而访问此值数组。
/**
* Create an array containing integers.
*/
int array[30];
array[0] = 0;
array[1] = 1;
...
array[29] = 29;
/**
* Create a pointer to an array.
*/
int (*pointer)[30];
/**
* Tell the pointer where the data is.
*/
pointer = &array;
/**
* Access the data through the pointer.
*/
(*pointer)[1] = 999;
/**
* Print the data through the array.
* ...and notice the output.
*/
printf("%d", array[1]);指针数组
如果有指向值的指针数组,则整个指针数组是一个变量,数组中的每个指针引用的是值所在的内存中的其他地方。
您可以访问这个数组及其内部的指针,而不需要取消引用,但是为了从数组中达到某个值,您必须取消引用数组中的一个指针。
/**
* Create an array containing pointers to integers.
*/
int *array_of_pointers[30];
array_of_pointers[0] = 0;
array_of_pointers[1] = 1;
...
array_of_pointers[29] = 29;发布于 2013-11-21 11:51:27
指向数组的指针
int a[10];
int (*ptr)[10];这里,ptr是一个指向10个整数数组的指针。
ptr = &a;现在ptr指向由10个整数组成的数组。
您需要插入ptr,以便以(*ptr)[i]代码的身份访问数组元素,如下示例所示:
样本代码
#include<stdio.h>
int main(){
int b[2] = {1, 2};
int i;
int (*c)[2] = &b;
for(i = 0; i < 2; i++){
printf(" b[%d] = (*c)[%d] = %d\n", i, i, (*c)[i]);
}
return 1;
}输出:
b[0] = (*c)[0] = 1
b[1] = (*c)[1] = 2指针数组
int *ptr[10];在这里,ptr[0],ptr[1]....ptr[9]是指针,可以用来存储变量的地址。
示例:
main()
{
int a=10,b=20,c=30,d=40;
int *ptr[4];
ptr[0] = &a;
ptr[1] = &b;
ptr[2] = &c;
ptr[3] = &d;
printf("a = %d, b = %d, c = %d, d = %d\n",*ptr[0],*ptr[1],*ptr[2],*ptr[3]);
}产出:a= 10,b= 20,c= 30,d= 40
发布于 2013-11-21 11:50:30
指向数组的指针
指向数组的指针将指向数组的起始地址。
int *p; // p is a pointer to int
int ArrayOfIntegers[5]; // ArrayOfIntegers is an array of 5 integers,
// that means it can store 5 integers.
p = ArrayOfIntegers; // p points to the first element of ArrayOfIntegers指针数组
指针数组将包含指向不同变量的多个指针。
int* ArrayOfPointers[2]; // An array of pointers which can store 2 pointers to int
int A = 1;
int B = 2;
int *PointerToA ;
PointerToA = &A ; // PointerToA is a pointer to A
int *PointerToB ;
PointerToB = &B ; // // PointerToA is a pointer to A
ArrayOfPointers[0] = PointerToA ; // ArrayOfPointers first element points to A
ArrayOfPointers[1] = PointerToB ; // ArrayOfPointers second element points to Bhttps://stackoverflow.com/questions/20120054
复制相似问题