[英]C language: structs and character arrays
當我嘗試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;
}
如果將char *
添加到value,對我來說效果很好。 沒有這個,我認為它是隱式的int。 這已從C99中刪除。 即使不是,您也顯然不應該將char *
作為整數傳遞。 此外,我不知道您是否還允許混合使用隱式int和顯式類型( struct aac *
)。
另一個問題是您的第二個malloc無法移植。 在32位計算機上,它將分配25個指針,而在64位12.5上,則沒有意義。 使用類似:
b.data = malloc ( sizeof(char *) * 25 );
您可能希望將25聲明為常量。
也許這個例子可能會有所幫助:
#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...
希望有幫助...至少有一點:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.