简体   繁体   English

将指针的值分配给指针数组中的指针

[英]Assign value of pointer to pointer in array of pointers

I would like to assign a character in a string to the first character of string in array of strings, equivalently I would like to assign a pointer in an array of pointers to the value of another pointer. 我想将一个字符串中的字符分配给字符串数组中字符串的第一个字符,等效地,我想将一个指针数组中的指针分配给另一个指针的值。

I have tried the following: 我尝试了以下方法:

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

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

These seem like they are assigning the value of value of the first pointer. 这些似乎是他们在分配第一个指针的value的值。

I keep getting a segmentation fault error. 我不断收到细分错误错误。

I realized that I was misunderstanding what happens when an array of pointers is created. 我意识到我误解了创建指针数组时会发生什么。 I assumed that C actually created the pointers in an array and didn't just allocate space for them. 我以为C实际上是在数组中创建了指针,而不仅仅是为它们分配空间。

The fix: 解决方法:

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 */

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

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