使用C中的Pointer变量读取一行



[Code]

#include <stdio.h>
//#include <conio.h>  // getch()
int main(int argc, char *argv[])
{
char c, *s;
printf("Enter the number...n");
while ((c=getchar()) != EOF && c != 'n' && c != 't') {
putchar(c);
*s++ = c;    // **What is wrong in here, the code is crashing!!**
}
printf("The number: %sn", s);
return 0;
}

输出:

c:\works\workout\c>gcc tmp.c-o tmp

c: \works \ workout \c>tmp

输入数字。。。

434232

4

c: \works \ workout \c>

预期输出:实际给定的输入数字/字符串!(如434232(

应仅使用"pointer"输出(不使用"scanf"、"char s[10]"等(

提前感谢!

首先,必须分配s,因为它是一个指针。

其次,声明int c而不是char c,因为函数getchar()putchar()的定义为:

int putchar(int c); 
int getchar(void);

最后,使用s[i] = ...而不是*s++ =

完整的代码(在这个代码中,我使用realloc函数来分配每次从键盘获得新值的时间(:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int c;
char *s = malloc(sizeof(char) + 1);
if (s == NULL)
exit(-1);
printf("Enter the number...n");
int i = 0;
while ((c=getchar()) != EOF && c != 'n' && c != 't') {
putchar(c);
s[i] = c; 
// re-allocate because the size of s has to increase to store the new value
s = realloc(s, sizeof(char));
if (s == NULL)
exit(-1);
i++;
}
printf("The number: %sn", s);
return 0;
}

最新更新