c - 指向字符宽度 typedef 的指针数组

标签 c pointers char malloc typedef

我正在尝试创建一个指向 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 或“安全”的东西,将字符缓冲区(字符串)的长度传递到其中以阻止内存被乱写,这是很好的。

编辑:

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

strlcpy

strcpy_s

关于c - 指向字符宽度 typedef 的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19963431/

相关文章:

c - 为什么不能将 `char **` 传递给在 C 中采用 `const char **` 的函数?

c++ - 指针初始化和分配问题

c++ - char *blah = "hello"是如何工作的?

c# - 在 C# 中将 char 转换为 int

c++ - 将 const char* 传递给方法,但得到 char const * 错误

c++ - 确定库的地址内存

c++ - 在 C/C++ 程序中使用汇编程序优化某些功能真的值得吗?

带参数调用Linux服务

c - 如何在 C 中轻松获得正则表达式选择?

c++ - 从 void 指针增加值