【问题标题】:Assign value of pointer to pointer in array of pointers将指针的值分配给指针数组中的指针
【发布时间】:2015-09-05 18:08:37
【问题描述】:

我想将字符串中的一个字符分配给字符串数组中字符串的第一个字符,相当于我想将指针数组中的一个指针分配给另一个指针的值。

我尝试了以下方法:

char ** array=malloc(sizeof(char*)*10);
char * str="like";

*(array[0])=*str;
*(array[0])=str[0];
**(array)=*str;
**(array)=str[0];

这些看起来像是在分配第一个指针的值。

我不断收到分段错误错误。

【问题讨论】:

  • array of strings 是数组的数组。您只为第一个数组分配内存(顺便说一下,那个数组将保存另一个数组 - 不正确),您应该遍历 array 的元素并为另一个数组分配内存。在 C 中查看 google 2d 数组
  • 您需要正确的心态。使用方框和指针图,例如rose-hulman.edu/Users/faculty/young/CS-Classes/archive/… 那么一切都会变得清晰。
  • 您在哪台计算机上的指针大小可以为 1、2、5 或 10(您分配的 10 个字节的除数)?
  • @Weather Vane:好的,我刚刚修好了。
  • @dylan7,看这里rextester.com/WSKM94472

标签: c arrays pointers


【解决方案1】:

我意识到我误解了创建指针数组时会发生什么。我假设 C 实际上在数组中创建了指针,而不仅仅是为它们分配空间。

修复:

char ** array = malloc(sizeof(char *) * 10);
    char tok = *ts; /* create character that has value of a pointer */

    char *token =&tok; /* create new pointer that points to same value as *ts but in a different address */
    array[0]=token; /* assign the pointer */

【讨论】:

    猜你喜欢
    • 2016-04-19
    • 2011-04-02
    • 2013-12-10
    • 2018-05-16
    • 1970-01-01
    • 2014-08-23
    • 2014-05-13
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多