gpt4 book ai didi

c - 我正在尝试使用 malloc 函数为数组分配内存,但值未正确扫描。谁能解释一下吗?

转载 作者:行者123 更新时间:2023-11-30 17:25:16 25 4
gpt4 key购买 nike

所以我被要求编写一个程序来测试用户输入的整数序列是否是回文(向后读取与向前读取相同)。我不知道如何动态分配内存以便输入可以具有可变长度。在代码中,您可以看到用户输入了序列中的元素数量 n。但在编译期间,当输入 n 个整数时,什么也没有发生。代码有什么问题吗?请尽可能详细地解释一下,如果您知道任何好的引用资料,请分享!!我正在努力处理指针和数组。

#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n, x;
int* intarray;
printf("\nHow many integers are there?: \n");
scanf("d", &n);
intarray = (int*)malloc(n * sizeof(int));
printf("\nPlease enter the values:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &intarray[i]);
}
n = n - 1;
x = n / 2;
for (i = 0; i <= x; i++)
{
if (intarray[i] != intarray[n - i])
{
printf("\nThis is not a palindrome\n");
return;
}

if (i = x)
{
printf("\nThis is a palindrome\n");
}
}
return;
}

最佳答案

#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n, x;
int* intarray;
printf("\nHow many integers are there?: \n");
scanf("%d", &n); // and as mentioned by all above type specifier % is missing in %d (for integer type)
intarray = (int*)malloc(n * sizeof(int));
printf("\nPlease enter the values:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &intarray[i]);
}
n = n - 1;
x = n / 2;
for (i = 0; i <= x; i++)
{
if (intarray[i] != intarray[n - i])
{
printf("\nThis is not a palindrome\n");
return;
}

if (i = x)
{
printf("\nThis is a palindrome\n");
}
}
return 0; // as your main()'s return type is int, you should should return an integer value
}

关于c - 我正在尝试使用 malloc 函数为数组分配内存,但值未正确扫描。谁能解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091612/

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