gpt4 book ai didi

c - 将数组作为数组与作为指针传递给函数

转载 作者:太空宇宙 更新时间:2023-11-04 06:34:01 24 4
gpt4 key购买 nike

我是 C 的新手,我正在寻找将数组传递给函数并访问元素的方法。

我发现有 3 种方法可以做到这一点。

  1. 传入一个数组,函数将参数指定为数组
  2. 的类型
  3. 传入一个数组,函数将参数指定为指针
  4. 的类型
  5. 传入第一个元素的地址(其实这个地址等于数组地址,我觉得这个和方法2是一样的)

我不明白的是,使用方法1,传入的数组地址和函数中数组参数的地址不一样。使用方法一和方法二有什么区别。

代码:

#include <stdio.h>

void pass_by_array(int x[]);
void pass_by_pointer(int *x);
int main(void){
int i;
int base[5] = {3, 7, 2, 4, 5};
printf("address of first element in main %p\n", &base[0]);
printf("address of array in main %p \n\n", &base);
pass_by_array(base);
pass_by_pointer(base);
}

/* Pass in the array as type of int x [] */
void pass_by_array(int x[]){
printf("address of first element passed in: %p \n", &x[0]);
printf("address of array passed in: %p \n\n", &x);
}

/* Pass in the array as type of int pointer*/
void pass_by_pointer(int *x){
printf("passing in array by pointer, address: %p",x);
}

输出:

address of first element in main 0xbfcea3ac
address of array in main 0xbfcea3ac

address of first element passed in: 0xbfcea3ac
address of array passed in: 0xbfcea390

passing in array by pointer, address: 0xbfcea3ac%

最佳答案

这一行:

printf("address of array passed in: %p \n\n", &x);

错了。你打印出来的不是数组的地址,而是数组指针所在的局部变量的地址。(是的,x其实就是一个指针。)打印出x就可以了:

printf("address of array passed in: %p \n\n", x);

答案是,在这种情况下,以何种方式声明并不重要。 C 中的 int[]int* 有时可以互换,这就是它们互换的情况之一。

进一步阅读:

关于c - 将数组作为数组与作为指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17094796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com