【发布时间】:2013-11-13 20:15:00
【问题描述】:
我正在尝试创建一个指向 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));
就是这样……
【问题讨论】:
-
那么,你遇到了什么错误,在哪一行代码上?
-
虽然 C++ 有
->*运算符,但我认为它在 C 中不可用... -
它是,至少在我的编译器上,
-
如果这是 C(如标记),please don't cast the return value of
malloc(). -
@user2533527 你用的是什么编译器?因为en.wikipedia.org/wiki/… 不同意你所说的……虽然它在 C++ 中可用并且做一些不同的事情。
标签: c pointers char malloc typedef