如何将二维字符串数组分配给字符指针数组?
How to assign 2D string array to char pointer array?
我一直在尝试将 char words[x][y] 分配给 char* pointer[x]。但是编译器给我一个错误
array type 'char *[5]' is not assignable
pointer = &words[0]
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char words[5][10]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
char *pointer[5];
pointer = &words[0];
char **dp;
dp = &pointer[0];
int n;
for(n=0; n<5; n++){
printf("%s\n", *(dp+n));
}
return 0;
}
但是代码在
时有效
char *pointer[5]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
char **dp;
dp = &pointer[0];
我只需要将二维数组正确分配到指针数组即可!!
pointer = &words[0];
上的错误发生是因为您正在使用 'array of pointers' 并使其指向第一个字符数组,因为指针指向 char 这没有意义。尝试类似的东西:
char *pointer[5];
pointer[0] = &words[0][0];
pointer[1] = &words[1][0];
//...
这将使您的指针指向字符串的第一个 char
(我认为这是所需的行为?)
不幸的是,你不能按照你想要的方式去做。 char words[5][10]
不会将指针本身存储在任何地方,它实际上是一个 50 个字符的数组。 sizeof(words) == 50
在记忆中,它看起来是这样的:
'A','p','p','l','e','[=10=]',x,x,x,x,'B','a'...
这里没有地址。当您执行 words[3] 时,它只是 (words + 3),或者 (char *)words + 30
另一方面,char *pointer[5]
是一个包含五个指针的数组,sizeof(pointer) == 5*sizeof(char*)
。
因此,您需要通过计算偏移量手动填充 pointer
数组。像这样:
for (int i = 0; i < 5; i++) pointer[i] = words[i];
我一直在尝试将 char words[x][y] 分配给 char* pointer[x]。但是编译器给我一个错误
array type 'char *[5]' is not assignable pointer = &words[0]
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char words[5][10]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
char *pointer[5];
pointer = &words[0];
char **dp;
dp = &pointer[0];
int n;
for(n=0; n<5; n++){
printf("%s\n", *(dp+n));
}
return 0;
}
但是代码在
时有效char *pointer[5]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
char **dp;
dp = &pointer[0];
我只需要将二维数组正确分配到指针数组即可!!
pointer = &words[0];
上的错误发生是因为您正在使用 'array of pointers' 并使其指向第一个字符数组,因为指针指向 char 这没有意义。尝试类似的东西:
char *pointer[5];
pointer[0] = &words[0][0];
pointer[1] = &words[1][0];
//...
这将使您的指针指向字符串的第一个 char
(我认为这是所需的行为?)
不幸的是,你不能按照你想要的方式去做。 char words[5][10]
不会将指针本身存储在任何地方,它实际上是一个 50 个字符的数组。 sizeof(words) == 50
在记忆中,它看起来是这样的:
'A','p','p','l','e','[=10=]',x,x,x,x,'B','a'...
这里没有地址。当您执行 words[3] 时,它只是 (words + 3),或者 (char *)words + 30
另一方面,char *pointer[5]
是一个包含五个指针的数组,sizeof(pointer) == 5*sizeof(char*)
。
因此,您需要通过计算偏移量手动填充 pointer
数组。像这样:
for (int i = 0; i < 5; i++) pointer[i] = words[i];