-2

I have the following code

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


int main()
{
  char *A, B, C, D;
  printf("Enter name A:");
  scanf("%s", &A);


  printf("Enter name B:");
  scanf("%s", &B);

  printf("Enter name C:");
  scanf("%s", &C);

  printf("Enter name D:");
  scanf("%s", &D);

  printf("%s, %s, %s, %s \n", A, B, C, D);    

  return 1;
}

it accepts four strings but crashes before printing them out?

the second thing I would like to do, is pass those strings(A,B,C,D) to a function that accepts void pointers, would I have to cast them to a void pointer first??

Ammar S
  • 91
  • 8
  • 1
    Your problem is that B,C,D are not `char*`! You need to attach a `*` before each of them when you declare them (not the only problem - also need to allocate memory) – SomethingSomething Mar 15 '15 at 15:40
  • 1
    Change the declaration line to: `char *A, *B, *C, *D;` and of course you need to use `malloc()` to allocate dynamic-memory, or to use local char-arrays instead – SomethingSomething Mar 15 '15 at 15:41
  • 1
    Note that `char *A, *B, *C, *D;` isn't the same as `char *A, B, C, D;` – Spikatrix Mar 15 '15 at 15:42

1 Answers1

6

You need to allocate space for A, you are using scanf() the wrong way, the "%s" specifier does not allocate space for the destination variable.

You can just allocate space in the stack by declaring A as an array of fixed size, like this

char A[100];

then

if (scanf("%99s", A) != 1)
 {
    printf("unexpected problem, probably `EOF'\n");
    return -1;
 }

also, this

char *A, B, C, D;

is not what you apparently think, the * only applies to A there, so maybe you meant

char *A, *B, *C, *D;

One last thing, "%s" specifier expects a char * i.e. a char pointer, by using the & address of operator you are passing char ** which is wrong, so you don't need it in this case.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • would it be better to use dynamic memory allocation since I don't know what the size if the incoming string is?? is there a draw back to this method?? – Ammar S Mar 15 '15 at 15:56
  • keep in mind, that I want to pass these strings to a function that accepts a void pointer – Ammar S Mar 15 '15 at 15:56
  • It would be too hard, and you can pass them to a function taking `void *` or `char *` because `void *` is converted to any kind of pointer and viceversa, so that's why you for example don't need to cast `malloc()`, what you can't do is return them from a function. – Iharob Al Asimi Mar 15 '15 at 15:57