如何正确地将char数组指定给指针?

时间:2014-05-17 18:46:58

标签: objective-c c

我应该如何分配" elCorteIngles"内存地址到我的指针?

xcode说"数组类型' char * [20]'不可分配"

这是代码,提前谢谢:

int main(int argc, const char * argv[])
{

@autoreleasepool {

    char elCorteIngles[20] = "Av. Jaime III";
    char *paginasAmarillas[20];

    paginasAmarillas = &elCorteIngles;

    NSLog(@"Según ECI su dirección es           %s", elCorteIngles);
    NSLog(@"Según PagsAmarillas su dirección es %s", *paginasAmarillas);


}
return 0;
}

2 个答案:

答案 0 :(得分:3)

你就是这样做的,

  char elCorteIngles[20] = "Av. Jaime III";

  char *paginasAmarillas = NULL;

  paginasAmarillas = elCorteIngles;

因为,elCorteIngles已经是一个数组,它指向数组的第一个地址。因此,您必须将elCorteInfles的第一个地址分配给paginasAmarillas。由于* paginasAmarillas是地址指向的值,因此您必须将elCorteIngles连续位置的第一个位置的地址分配给指针初始指向的地址位置。

答案 1 :(得分:0)

C语言不允许您直接将字符串分配给字符数组。您可以像上面那样在初始化时分配字符串,也可以将字符移动到数组中。 C标准库函数strcpy()和strcat()通常用于修改字符串的内容。

例如:

char theString[10] = "ab";

分配一个10个字符的数组,并将字符串的前三个字符初始化为'a','b'和'\ 0',因为C字符串是以NULL结尾的。这相当于:

char theString[10];

theString[0] = 'a';
theString[1] = 'b';
theString[2] = '\0';

如果您希望theString说“abode”,那么您必须将这些字符复制到数组中。

strcpy(theString, "abcde");

标准库字符串函数包含在程序中:

#include <string.h>

strcat()函数用于连接字符串。

strcpy(theString, "abc");
strcat(theString, "123");

所以在你的情况下:

char elCorteIngles[20] = "Av. Jaime III";
char *paginasAmarillas;

paginasAmarillas = elCorteIngles;

strcpy(paginasAmarillas, "ABCDE");