简体   繁体   English

如何将二维字符串数组分配给 char 指针数组?

[英]How to assign 2D string array to char pointer array?

I've been trying to assign char words[x][y] to a char* pointer[x].我一直在尝试将 char words[x][y] 分配给 char* pointer[x]。 But compiler is giving me a error但是编译器给了我一个错误

array type 'char *[5]' is not assignable pointer = &words[0]数组类型 'char *[5]' 不可分配指针 = &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;
}

But the code works while但是代码有效

char *pointer[5]={"Apple", "Ball", "Cat", "Dog", "Elephant"};
char **dp;
dp = &pointer[0];

all I need is to correctly assign the 2D array into pointer array!!我所需要的只是将二维数组正确分配到指针数组中!!

Unfortunately, you can't do it the way you want.不幸的是,你不能按照你想要的方式去做。 char words[5][10] doesn't store the pointers themselves anywhere, it is effectively an array of 50 chars. char words[5][10]不会将指针本身存储在任何地方,它实际上是一个 50 个字符的数组。 sizeof(words) == 50

In memory, it looks something like:在内存中,它看起来像:

'A','p','p','l','e','\0',x,x,x,x,'B','a'...

There are no addresses here.这里没有地址。 When you do words[3] that is just (words + 3), or (char *)words + 30当您执行 words[3] 时,即 (words + 3) 或(char *)words + 30

On the other hand, char *pointer[5] is an array of five pointers, sizeof(pointer) == 5*sizeof(char*) .另一方面, char *pointer[5]是一个由五个指针组成的数组, sizeof(pointer) == 5*sizeof(char*)

So, you need to manually populate your pointer array by calculating the offsets.因此,您需要通过计算偏移量来手动填充pointer数组。 Something like this:像这样的东西:

for (int i = 0; i < 5; i++) pointer[i] = words[i];

The error on pointer = &words[0]; pointer = &words[0]; happens because you are taking an 'array of pointers' and make it point to the first array of characters, since pointer points to a char this makes no sense.发生是因为您正在使用“指针数组”并使其指向第一个字符数组,因为指针指向 char 这没有任何意义。 Try something like:尝试类似:

char *pointer[5];
pointer[0] = &words[0][0];
pointer[1] = &words[1][0];
//...

This will make your pointers to point at the first char of your strings (which I assume is the desired behavior?)这将使您的指针指向字符串的第一个char (我认为这是所需的行为?)

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

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