我试图使用malloc函数为数组分配内存,但是这些值没有正确地扫描进来。有人能解释一下吗?

我试图使用malloc函数为数组分配内存,但是这些值没有正确地扫描进来。有人能解释一下吗?,c,arrays,pointers,dynamic-memory-allocation,C,Arrays,Pointers,Dynamic Memory Allocation,因此,我被要求编写一个程序,测试用户输入的整数序列是否是回文序列,前后读取是否相同。我不知道如何动态分配内存,以便输入可以是可变长度的。在代码中,您可以看到用户输入了其序列中的元素数n。但在编译过程中,当输入n个整数时,什么也不会发生。代码有什么问题?请尽可能详细地解释,如果你知道任何好的参考资料,请分享!!我正在努力处理指针和数组 #include <stdio.h> #include <stdlib.h> int main () { int i, n, x;

因此,我被要求编写一个程序,测试用户输入的整数序列是否是回文序列,前后读取是否相同。我不知道如何动态分配内存,以便输入可以是可变长度的。在代码中,您可以看到用户输入了其序列中的元素数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;
}
问题在于scanfd,&n;实际上不将任何内容读入n的语句,如要读取整数,应使用%d而不是d。

2更改:

一,

%d是扫描整数的格式说明符

二,

无需施放malloc

scanfd,&n;缺少%。
scanf("%d", &n);
intarray = malloc(n * sizeof(int));
#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
}