C语言: structs and character arrays

标签 c struct

当我尝试 printf() 数据的值时,我什么也得不到,但如果我这样做 date = "text" 它就会起作用。有谁知道原因吗?

struct aac { char **data; };

int main ( ) {
    char* value = malloc ( 100 );
    strcpy ( value, "test" );
    struct aac b;  
    b.data = malloc ( 100 );  
    cake ( value, &b );  
    donut ( &b );
    return 0;  
}

int cake ( char *value, struct aac *c ) {  
    c->data[0] = value;  
    return 0;  
}

int donut ( struct aac *b ) {  
    printf ( "%s", b->data[0] );
    return 0;
}

最佳答案

也许这个例子可能有帮助:

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <errno.h>

struct aac {
   char **pastries;
};

void
init_pastries (struct aac * rec_p, int max)
{
  /* Allocate space for max #/pastries, plus a NULL delimiter */
  int nbytes = sizeof (char *) * (max+1);
  rec_p->pastries = (char **)malloc (nbytes);
  memset (rec_p->pastries, 0, nbytes);
  printf ("init_pastries: max #/pastries: %d, malloc: %d bytes...\n",
    max, nbytes);
}

void
add_pastry (char * name, int i, struct aac *rec_p)
{
  int nbytes = strlen (name) + 1;
  rec_p->pastries[i] = (char *)malloc (nbytes);
  strcpy (rec_p->pastries[i], name);
  printf ("add_pastry (%s): malloc= %d bytes...\n",
    name, nbytes);
}

void
print_pastries (struct aac * rec_p)
{
  char **s = NULL;
  for (s = rec_p->pastries; (*s); s++)
    printf ("pastry: %s...\n", *s);
}

int
main ( ) {
    struct aac rec;
    init_pastries (&rec, 5);
    add_pastry ("cake", 0, &rec);
    add_pastry ("donut", 1, &rec);
    print_pastries (&rec);
    return 0;
}

这是示例输出:

gcc -o tmp tmp.c

./tmp 
  init_pastries: max #/pastries: 5, malloc: 24 bytes... add_pastry
  (cake): malloc= 5 bytes... add_pastry
  (donut): malloc= 6 bytes... pastry:
  cake... pastry: donut...

“希望有帮助......至少有一点:)

关于C语言: structs and character arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3562469/

相关文章:

C程序: keyboard does not recognise enter using getch()

c++ - C 头文件中的函数声明与其在 .cpp 文件中的定义之间的一致性

c++ - 为什么 CUDA 固定内存这么快?

c - 如何使用换行符退出 scanf 循环。当前无限循环

c - 缓冲区溢出攻击后如何 "cleanly"终止程序

使用结构体计算复数

c - 我在这段代码中做错了什么?

c - 使用字符串的链接列表

c - 定义指向结构数组的指针

c - 我无法 typedef 指向已进行 typedef 编辑的结构的指针