tags:

views:

87

answers:

2

When I try to printf() the value of data, I get nothing, but if I were to do date = "text" It would work. 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;
}
A: 

It works fine for me if you add char * to value. Without that, I think it's implicit int. This is removed from C99. Even if it weren't, you should clearly not be passing a char * as an integer. Further, I don't know if you're even allowed to mix implicit int and explicit types (struct aac *).

Another issue is that your second malloc is not portable. On a 32-bit machine it will allocate 25 pointers, but on a 64-bit 12.5, which doesn't make sense. Use something like:

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

You might want to declare 25 as a constant somewhere.

Matthew Flaschen
It prints out the value for you?
Jay
A: 

Hi -

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 :)

I am not sure what i am over looking. Thanks i will have to give this a look over since it works perfectly.
Jay
Hi - I wasn't sure exactly what your question was, so I put together an example illustrating a couple of the things I thought you might have been unclear about.I hope at least some of the example might be useful to you.In any case, please do post back when you find a solution, and please mark the problem "solved"