我是编程的初学者,并获得了有关动态分配内存的作业。其中一个预期的输出是printf语句,其中所有输入的输入(整数)连续打印在一行中。我已经设法在一个for循环中打印printf,但那是不应该的。如何在一个代码行中打印它们?这是代码:
int main()
{
int how_many_integers, count, entered_integers, i, *pSize;
printf("\nHow many integers are you going to type?\n");
scanf("%i", &how_many_integers);
getchar();
// Allocates memory for the integers.
pSize = malloc (how_many_integers * sizeof(int));
// Checks if the integer is 0, and/or reads in all the integers.
if (how_many_integers == 0)
{
printf("No numbers were given.\n");
exit(0);
}
printf("Please enter your integers.\n");
for (int i = 0; i < how_many_integers; i++)
{
scanf("%i", &entered_integers);
count++;
pSize[i] = entered_integers;
}
for (int i = 0; i < how_many_integers; i++)
{
printf("Number: %i\n", *(pSize+i));
}
free(pSize);
printf("Count: %i", count);
return 0;
}
答案 0 :(得分:4)
试试这个:
printf("Numbers:");
for (int i = 0; i < how_many_integers; i++)
{
printf(" %i", *(pSize+i)); // No \n
}
printf("\n"); // if you want a new line at the end
这应该会产生类似
的输出 Numbers: 1 2 3 4 5
正如其他人提到的那样,您的count
变量永远不会被初始化。将其初始化为0。