简体   繁体   English

C语言:结构和字符数组

[英]C language: structs and character arrays

When I try to printf() the value of data, I get nothing, but if I were to do date = "text" It would work. 当我尝试printf()数据值时,我什么也没得到,但是如果我要做date = "text"它将起作用。 Anyone know the reason for that? 有人知道原因吗?

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;
}

It works fine for me if you add char * to value. 如果将char *添加到value,对我来说效果很好。 Without that, I think it's implicit int. 没有这个,我认为它是隐式的int。 This is removed from C99. 这已从C99中删除。 Even if it weren't, you should clearly not be passing a char * as an integer. 即使不是,您也显然不应该将char *作为整数传递。 Further, I don't know if you're even allowed to mix implicit int and explicit types ( struct aac * ). 此外,我不知道您是否还允许混合使用隐式int和显式类型( struct aac * )。

Another issue is that your second malloc is not portable. 另一个问题是您的第二个malloc无法移植。 On a 32-bit machine it will allocate 25 pointers, but on a 64-bit 12.5, which doesn't make sense. 在32位计算机上,它将分配25个指针,而在64位12.5上,则没有意义。 Use something like: 使用类似:

b.data = malloc ( sizeof(char *) * 25 );

You might want to declare 25 as a constant somewhere. 您可能希望将25声明为常量。

Perhaps this example might help: 也许这个例子可能会有所帮助:

#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;
}

Here's sample output: 这是示例输出:

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...

'Hope that helps ... at least a bit :) 希望有帮助...至少有一点:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM