0

I'm new to structs and pointers and I can't see what's wrong with this code:

struct {
    int id;
    char* name;
} cap[50];

void xep() {
    int i, n;
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        cap[i].id = i;
        scanf("%c", cap[i].name);
        printf("%d %s\n", cap[i].id, cap[i].name);
    }
}

When calling the xep function in main, it only prints:

    0 (null)
    1 (null)
    2 (null)

Like it ignores everything I input after n. Any ideas?

Antti Degl
  • 69
  • 8

1 Answers1

1

char* name is a pointer, but you haven't allocated any memory to it. Either give it a fixed size char name[100] or alloc some memory. Your scanf is just getting 1 character, you probably want %s (string) instead of %c (character)

Scott C
  • 1,660
  • 1
  • 11
  • 18
  • How do I malloc exactly how much memory I need for the string? *name = malloc (1 * sizeof(char)) in the struct; what after? – Antti Degl Dec 02 '14 at 12:02
  • It's really time to do some searches @AnttiDegl. :) If you truly just want 1 character, initialise an array. If you want each name to be exactly the right length, you'll have to scanf into a char array of the maximum allowed length first, then strcpy (after malloc) http://stackoverflow.com/questions/1538420/difference-between-malloc-and-calloc http://stackoverflow.com/questions/12306591/ensure-scanf-only-reads-so-many-characters-in-a-string – Scott C Dec 02 '14 at 22:33