我正在尝试创建一个指向 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));
就是这样...
最佳答案
尝试:
strcpy((taa->a[1]), "Peter");
另请注意,[1]
正在访问数组中的第二个元素;第一个使用 [0]
。最好使用 strncpy 或“安全”的东西,将字符缓冲区(字符串)的长度传递到其中以阻止内存被乱写,这是很好的。
编辑:
非标准的安全字符串函数:
关于c - 指向字符宽度 typedef 的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19963431/