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

标签 c arrays pointers dynamic-memory-allocation

所以我被要求编写一个程序来测试用户输入的整数序列是否是回文(向后读取与向前读取相同)。我不知道如何动态分配内存以便输入可以具有可变长度。在代码中,您可以看到用户输入了序列中的元素数量 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/

相关文章:

c++ - 使用数组的文件输出不正确

c++ - 我如何着手允许类类型的对象未初始化并在不使用指针的情况下识别这种情况?

使用 atoi/sprintf 将整数转换为字符串

c - 如何将结构初始化为安全值

c - 获取pid的进程名

javascript - 在数组中查找具有相似值的数字

c++ - 复制指针数组并跳过某些索引

c - C语言中的for循环,for(i = len; i--;)

c - 为什么这个 NetBeans 测试代码不能正确链接?

c - 为什么动态分配的二维数组会得到 "Segmentation fault"?