【问题标题】:Is it possible to still address the individual elements of an array via a pointer?是否仍然可以通过指针寻址数组的各个元素?
【发布时间】:2011-12-05 22:34:39
【问题描述】:

我正在尝试编写一个程序,它将两个数字相乘,但以二进制输出结果,显示计算(即移动行)。我将二进制数存储为 32 个字符的数组,每个元素为 1 或 0。

我有一个函数可以将十进制转换为二进制字符数组,但是我的数组只存在于函数中,但我需要在另一个函数中以及 main 中使用该数组。我在想有可能使用指针从我的转换器函数中更改 main 中数组的值,因此该数组将存在于 main 中并且可以在其他函数中使用。这可能吗?

我已经声明了两个指向字符数组的指针:

char (*binOne)[32];
char (*binTwo)[32];

如果我将指针作为参数传递给函数,我还能访问每个元素吗?对不起,如果我在这里没有多大意义。

【问题讨论】:

  • 向我们展示代码。你可以有一个像void toBinary(char *buff, int num) 这样的函数,然后是char binary[32];toBinary(binary, 9001)

标签: c arrays function pointers


【解决方案1】:

在 C 中,大多数时候数组的行为类似于指向其第一个元素的指针,所以您可能想要做的是:

void foo(char* arr){
  //some stuff, for example change 21-th element of array to be x
  arr[20] = 'x';
}

int main(){
  char binOne[32];
  char binTwo[32];

  // change array binOne
  binOne[20] = 'a';

  foo(binOne);

  // now binOne[20] = 'x'

  foo(binTwo);

  // now binTwo[20] = 'x'
}

【讨论】:

  • 那么我可以在 foo 中使用 arr[1] 等吗?
  • 我的意思是,arr[1]、arr[2] 等会引用数组 arr 中的第一个、第二个等元素吗?
  • C 中的 arr[0] 是第一个元素,arr[1] 是第二个元素,依此类推。
  • 勉强 +1。数组不是实际上是指向其第一个元素的指针;相反,在许多情况下,数组变量被隐式转换为这样的指针。请注意,sizeof(binOne) 至少为32,而sizeof(arr) 通常为48,具体取决于平台。
  • @Alex:在 C 中,除非您明确设置堆栈变量的值,否则它将是随机的。
【解决方案2】:

我作为评论添加的内容的延续:

在 C 语言中,如果你想修改/返回一个数组,你可以通过传递一个指向它的指针作为参数来实现。例如:

int toBinary(char *buff, int num) { /* convert the int, return 1 on success */ }
...
char buff[32];
toBinary(buff, 9001);

在C语言中,数组的名字它的地址,它是第一个元素的地址:

buff == &buff == &buff[0]

【讨论】:

    【解决方案3】:

    是的,这是可能的。但是你只需要一个指向数组的指针而不是指针数组。 你需要像原型一样 例如

    void int_to_arr(int n, char *arr);
    void arr_to_int(int *n, char *arr);
    
    in main(){
    
       char *binarr = calloc(32, sizeof(char));
       int n = 42;
       int_to_arr(n, binarr);
    }
    
    void int_to_arr(int n, char *arr)
    {
       //do you conversion
       //access array with 
       // arr[i]
    }
    
    void arr_to_int(int *n, char *arr)
    {
       //do you conversion
       //access array with 
       // *n = result;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 2013-05-26
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多