-1

I tried this with an integer array and it worked.

#include<stdio.h>
 main()
{
  int c[5]; int i;

  printf("\nEnter the integers (max.5):\n ");

  for(i=0; i<=4; i++)

  scanf("%d", &c[i]);

for(i=0; i<=4; i++)

  display(&c[i]);

}

display(int *k)

{ printf("\nThe integers you entered are: %d", *k);
}

The output was:

Enter the integers (max.5):
 1
4
3
7
6

The integers you entered are: 1
The integers you entered are: 4
The integers you entered are: 3
The integers you entered are: 7
The integers you entered are: 6
--------------------------------
Process exited after 3.182 seconds with return value 32
Press any key to continue . . .

But when i tried to pass a character array it gives a weird output and accepts only 3 characters.

#include<stdio.h>
 main()
{
  char c[5]; int i;

  printf("\nEnter the characters (max.5): ");

  for(i=0; i<=4; i++)

  scanf("%c", &c[i]);

for(i=0; i<=4; i++)

  display(&c[i]);

}

display(char *k)

{ printf("\nThe characters you entered are: %c", *k);
}

The output was:

Enter the characters (max.5):
a
s
f

The characters you entered are: a
The characters you entered are:

The characters you entered are: s
The characters you entered are:

The characters you entered are: f
--------------------------------
Process exited after 3.875 seconds with return value 34
Press any key to continue . . .

Question: I can't understand why this happens and why it is accepting only 3 characters. Where i am wrong? and what corrections should i do?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
daya
  • 160
  • 2
  • 14
  • 3
    Well, I'd say, not to downvote a question based on obviousness. This is a good sample of how a question to be asked. lacks research effort, I agree, but for some it may be difficult to search if they don;t know what they're looking for. – Sourav Ghosh Jan 05 '18 at 09:45

1 Answers1

2

You can see that suddenly there is a line break. Well it consumed the \n and that is what is being assigned to c[i] as a result of scanf. Better use scanf(" %c",&c[i]). That will consume the \n that is left behind in the standard input. (The space consumes whitespaces so this will work).

Also using scanf should always be with a return value check. That helps you avoiding the error that you will run into if wrong input is given.

So it will be if(scanf(" %c",&c[i]) != 1){ /* error */ }

How to pass char array?

Well the thing is you can pass char array even more easily.

display(5,c);

void display(size_t len,char k[])
{
    for(size_t i = 0; i< len; i++)
     printf("\nThe characters you entered are: %c", k[i]);
}

In fact if you have a null terminated char array then it's even more easier to work with. Then you can simply print it with %s format specifier in printf.

printf("%s",c); // this will print the string(nul terminated char array).
Community
  • 1
  • 1
user2736738
  • 30,591
  • 5
  • 42
  • 56