如何使用指针将字符数组传递给函数?

时间:2018-01-05 09:39:20

标签: c arrays pointers

我尝试使用整数数组,但它确实有效。

#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);
}

输出结果为:

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 . . .

但是当我试图传递一个字符数组时,它会产生一个奇怪的输出并只接受3个字符。

#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);
}

输出结果为:

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 . . .

问题:我无法理解为什么会发生这种情况以及它为什么只接受3个字符。哪里错了?我应该做些什么改动?

1 个答案:

答案 0 :(得分:2)

你可以看到突然有一个换行符。好吧它消耗了\n,这就是c[i]导致scanf分配的内容。更好地使用scanf(" %c",&c[i])。这将消耗标准输入中遗留的\n。 (空间消耗空白,所以这将工作)。

同样使用scanf应始终使用return value check。这有助于您避免在给出错误输入时遇到的错误。

所以它将是if(scanf(" %c",&c[i]) != 1){ /* error */ }

如何传递char数组?

好吧,你可以更轻松地传递char数组。

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]);
}

事实上,如果你有一个空终止的char数组,那么它就更容易使用了。然后,您只需使用%s中的printf格式说明符进行打印。

printf("%s",c); // this will print the string(nul terminated char array).