0

I am attempting to store a string in a variable declared as char *name[2];. I am using scanf() to obtain the value from user input. This is my code so far and its currently not working:

#include <stdio.h>
#include <stdlib.h>
int main()
{   char *name[2];
    scanf("%s",name[0]);
    printf("%s",name[0]);
    return 0;
}
Magisch
  • 7,312
  • 9
  • 36
  • 52
  • See also: http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Lundin Feb 05 '16 at 11:59

2 Answers2

2

You haven't allocated any storage for the actual strings - char *name[2] is just an array of two uninitialised pointers. Try:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char name[2][80];
    scanf("%s", name[0]);
    printf("%s", name[0]);
    return 0;
}

or, if it really does need to be char *name[2], then you can allocate memory dynamically:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *name[2];
    name[0] = malloc(80);  // allocate memory for name[0] (NB: name[1] left uninitialised)
    scanf("%s", name[0]);
    printf("%s", name[0]);
    free(name[0]);         // free memory allocated for name[0]
    return 0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
0
char *name[2];

You have 2 pointers which are of type char

Allocate memory to the pointer using malloc() or any of its family membres.

name[0] = malloc(20);
Gopi
  • 19,784
  • 4
  • 24
  • 36