Friday, 15 April 2011

c - Why does my char array print random trailing characters? -



c - Why does my char array print random trailing characters? -

i'm finish novice programming , need help. after calling adds more once, , calling lists display stored in struct subject *a, first print of struct fellow member tag printed 12 characters correct, followed random trailing characters. on next iteration of loop, tag printed characters correct. i've tried lowering size of tag , seems removed trailing characters. happening here?

struct store { char call[7], tag[450]; int units; }; void adds(struct store *a, int *n) { char ecode[8], etags[450]; int f, error = 0; struct store *tempptr; scanf("%s", ecode); scanf("%d", &f); scanf("%s", etags); namelimit(ecode); if(initial(ecode) && occurrence(ecode, a, *n)) { printf("error.\n"); error++; } if(!error) { if(*n) { tempptr = realloc(a, *n + 1); = tempptr; } if(tempptr || !*n) { strcpy((a + *subctr) -> call, ecode); (a + *n) -> units = f; if (etags[0] == '.') (a + *n) -> tag[0] = '\0'; else strcpy((a + *n) -> tag, etags); printf("%s added.\n", ecode); *n = *n + 1; } else if(tempptr == null) { printf("no space.\n"); exit(1); } } } void lists(struct store *a, int n) { int i, j; for(i = 0; < n; i++) printf("%s %d %s\n", (a + i) -> call, (a + i) -> units, (a + i) -> tag); }

the sec argument realloc() byte size new allocation.

there's not plenty code shown sure, this:

tempptr = realloc(a, *subctr + 1);

should very probably be

tempptr = realloc(a, (*subctr + 1) * sizeof *a);

c arrays string random character

No comments:

Post a Comment