I am working on a program that, when specified by a number entered by the user, will only print out that number of characters. For example, if the user enters the number 10, then if 14 characters are entered (including newlines, blanks and tabs) only 10 characters will be printed. My code seems to work for the first three or so characters, then it prints out garbage. I'm not sure what is wrong.
我正在开发一个程序,当用户输入的数字指定时,该程序将只打印出该字符数。例如,如果用户输入数字10,则如果输入了14个字符(包括换行符,空格和制表符),则只打印10个字符。我的代码似乎适用于前三个左右的字符,然后它打印出垃圾。我不确定有什么问题。
#include <stdio.h>
#include <stdlib.h>
void findchars(char *abc, int number);
int main(void)
{
char *array; // the actual array
int num; // number of characters to read, becomes array value
printf("Number of characters:");
scanf_s("%d", &num);
array = (char *)malloc(num * sizeof(char));
findchars(array, num);
printf("The first %d characters: ", num);
puts(array);
free(array);
return 0;
}
void findchars(char *abc, int number)
{
int i;
printf("Type characters and I will stop at %d: ", number);
for (i = 0; i < number; i++)
{
abc[i] = getchar();
}
}
1 个解决方案
#1
2
You are passing non-zero-terminated array to puts. If you want your program to work just create your array 1 item bigger and add '\0' in the end.
您将非零终止数组传递给puts。如果你想让你的程序工作,只需创建更大的数组1项,最后添加'\ 0'。
Edit: like this
编辑:像这样
array = (char *)malloc((num+1) * sizeof(char));
and then right before puts
:
然后就在之前:
array[num] = '\0';
#1
2
You are passing non-zero-terminated array to puts. If you want your program to work just create your array 1 item bigger and add '\0' in the end.
您将非零终止数组传递给puts。如果你想让你的程序工作,只需创建更大的数组1项,最后添加'\ 0'。
Edit: like this
编辑:像这样
array = (char *)malloc((num+1) * sizeof(char));
and then right before puts
:
然后就在之前:
array[num] = '\0';