c - The printf functions print something that shouldn't, why? -
as can see images attached below, adding second element top of list create strange behaviour printf function.
the function add list node is:
void add_queuenode_top(item a) { if (head==null) { queueinit(a); } else { queueput_top(a); } return; } void queueinit(item a) { head=(link)malloc(sizeof(link*)); head->next=null; head->item=a; tail=head; printf("coda iniziallizata...\n\n"); } void queueput_top(item a) { link tmp; tmp=(link)malloc(sizeof(link*)); tmp->item=a; tmp->next=head; head=tmp; return; }
here functions handle items:
item fill_item() { item a; int i; for(i=0; i<dim-1; i++) { a.stringa[i]=rand(); } a.stringa[dim-1]='\0'; a.numero=rand(); printf("\noggetto generato: \n"); print_item(a); return a; } void print_item(item a) { printf("\nstringa elemento: "); printf("%s", a.stringa); printf("\nnumero elemento: %d\n", a.numero); }
here's link codeblock project i'm editing. function print_item(item a)
call "bugged" printf in item.c
module, while functions generate list item inside list.c
module.
any idea of can cause problem?
ps: i'm sorry captures located in italian
edit: definition of items:
typedef struct { char stringa[dim]; int numero; } item;
definition of link pointer:
typedef struct queuenode *link;
definition of link structure:
struct queuenode { item item; link next; };
you have several bugs - i'll try go through , find more of them you, specific problem you're asking related code:
for(i=0; i<dim-1; i++) { a.stringa[i]=rand(); } a.stringa[dim-1]='\0';
you're putting random number in each character - many of them may not interesting or printable characters in character set. that's why crazy output you're seeing. if want put random printable characters string, in more character-set-aware way.
some more problems:
these allocation lines wrong:
head=(link)malloc(sizeof(link*)); tmp=(link)malloc(sizeof(link*));
they should be:
head = malloc(sizeof(struct queuenode)); tmp = malloc(sizeof(struct queuenode));
that is, should allocate enough size entire
struct queuenode
, not pointer one. (or pointer pointer one, had). hiding pointer type insidetypedef
typedef struct queuenode *link;
1 of controversial style choices - prefer not to, since confuses issues 1 pretty fast.you're passing around lot of structures value in program. that's fine , valid c, it's bit non-idiomatic. people pass around pointers instead. if structure grows appreciable size, performance can start suffer badly result of of implicit memory copying going on.
Comments
Post a Comment