gpt4 book ai didi

c - 在C中打印出动态分配的内存

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:06 25 4
gpt4 key购买 nike

我完全是编程的初学者,并且得到了一个关于动态分配内存的作业。预期的输出之一是 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;
}

最佳答案

试试这个:

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

这应该会产生如下输出

数字:1 2 3 4 5

正如其他人提到的,您的 count 变量从未被初始化。将其初始化为 0。

关于c - 在C中打印出动态分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com