在指针数组中为指针赋值

时间:2021-12-02 19:32:38

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.

这些似乎是在分配第一个指针的值。

I keep getting a segmentation fault error.

我不断得到一个分割错误。

1 个解决方案

#1


0  

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

#1


0  

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