0

我正在尝试创建一个指向 char 的指针数组。我决定使用 typedef 定义,但我不知道做错了什么......

typedef struct _pp{
    char* a[10];
    int b;
}pp;

int main(){
  pp *taa = (pp* )malloc(sizeof(pp));
  taa->b = 2;
  printf("%d\n", taa->b);
  taa->a[1]=(char* )malloc(strlen("Peter")+1);
  strcpy((taa->*a[1]), "Peter");

  printf("%s\n", taa->*(a[1]));
  /*

/有效/

  int i;  
  int* a[5];
  for(i=0;i<5;i++){
    a[i]=(int* )malloc(sizeof(int));
    **(a+i)=i+100;
    printf("%d\n", **(a+i));
  */}

已编辑

这是好习惯吗?

  for(i=0;i<10;i++){
    taa->a[i]=(char* )malloc(strlen("Peter")+1);
    strncpy((taa->a[i]), "Peter", strlen("Peter"));
  }
  for(i=0;i<10;i++){
    printf("%s\n", taa->a[i]);
  }

问题 3)taa->*a[1]等价于ta.***(a + i)?

printf("%c",*taa->a[1]);  It dereference 'P' character, how i can get acces to 'e'?

printf("%c",*(taa->a[1]+0));

printf("%c",*(taa->a[1]+1)); 就是这样做...

4

2 回答 2

1

尝试:

strcpy((taa->a[1]), "Peter");

另请注意,[1]正在访问数组中的第二个元素;用于[0]第一个。最好使用strncpy或将字符缓冲区(字符串)的长度传递给“安全”的东西来阻止内存被乱写是好的。

编辑:

非标准的安全字符串函数:

字符串

strcpy_s

于 2013-11-13T20:18:11.377 回答
0

strcpy函数需要char*第一个参数的类型。在你的pp struct你有十个char*。您正在char*使用taa->a[1]. 所以删除*之后->会给你你需要的东西。这工作正常:

strcpy((taa->a[1]), "Peter");
于 2013-11-13T20:36:46.987 回答