简体   繁体   English

C-向函数内的双指针分配值

[英]C - Assigning a value to double pointer inside a function

I'm trying to understand C, specifically double-pointers and i came across this problem. 我试图理解C,特别是双指针,我遇到了这个问题。 I know for a single pointer (with removing the for loop, etc) that this concept would work, but i seem to be getting a seg fault at the located comment. 我知道对于单个指针(删除了for循环等),该概念将起作用,但是我似乎在所定位的注释中遇到了段错误。

Could someone explain why as to why i'm getting this error? 有人可以解释为什么我为什么收到此错误吗? I have a hunch that before i pass the address of myArgs i need to allocate some memory for it, but since i'm just doing a shallow copy, do i still need to allocate memory? 我有一种预感,在我传递myArgs的地址之前,我需要为其分配一些内存,但是由于我只是在进行浅表复制,因此我是否还需要分配内存?

void readArgs(int argc, char *argv[], char ***myArgs) {
   int i;
   for(i = 0; i < argc; i++) {
      /* crashes here @ i = 0 */
      *myArgs[i] = argv[i];
   }
}

int main(int argc, char *argv[]) {
   char **myArgs;
   int i;

   readArgs(argc, argv, &myArgs);
   for(i = 0; i < argc; i++)
      printf("arg[%d]: %s\n", i, myArgs[i]);
}

You're getting a segfault because myArgs is uninitialized. 由于myArgs未初始化,因此您遇到了段myArgs You should indeed allocate space with malloc . 您确实应该使用malloc分配空间。 You're not making a shallow copy; 您不是在进行浅表复制。 you're copying an array of pointers. 您正在复制一个指针数组。

That said, triple pointers are a code smell in C. You should never need more than ** . 也就是说,三重指针是C语言中的一种代码味道。您永远都不需要超过**

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM