期望'int *'但参数的类型为'int(*)[(long unsigned int)(n)]'

时间:2018-02-17 17:53:59

标签: c pointers

    User table - user details
    Post table - owned by a user
    Friends table - a table that stores the link between people. 

我不断收到期望'int asterix'的错误消息,但是对于& a1和& a2,参数类型为'int(asterix)[(long unsigned int)(n)]'。不知道为什么会这样做。该程序应该在数组中输入数字并取该数字加上6 mod 10然后输出转换后的数字。

2 个答案:

答案 0 :(得分:2)

是的,这是非常常见的事情 - 如果在数组上应用运算符的地址将为您提供指向数组的指针。

&应用于数组时,它不会转换为指向它的指针;第一个元素。那我们得到了什么?

int a[10]; &a将具有类型int(*)[10],这意味着它是指向包含10个元素的int数组的指针。

如果您打算在将数组传递给其他函数时更改数组,只需传递数组本身。它将被转换为指向它所包含的第一个元素的指针。通过访问指针,您可以对其进行更改。所以它就是为了这个目的。

在你的情况下,电话会是

 convert(a1, n, a2);

这里数组将被转换为指针 - 其类型为int*。,它与int (*)[]不同。编译器发现不匹配,并抱怨。

在大多数情况下,数组衰减为指向第一个元素的指针。 (例外情况是将其用作&sizeof等的操作数。

此外,您的函数中的代码会比较指针 - 您正在增加pa1,这使您可以访问超出数组的位置 - 这是未定义的行为(在您的情况下,未定义的行为原来是分段错误)。你应该改变这部分代码: -

while(p < a1+n)
{
   *a2=(*p+6)%10;
   a2++;
   p++;
}

但更好的是你可以做到这一点来复制整个事情

memcpy(a2,a1,n*sizeof(*a1));

或只是

for(int i = 0; i < n; i++)
    a2[i]=a1[i];

答案 1 :(得分:0)

我想你想要这个!

 #include<stdio.h>

void convert(int *a1, int n, int *a2);

int main()
{

    int n;

    printf("Enter the length of the array: ");
    scanf("%d", &n);


    int *a1 = new int[10];
    int *a2 = new int[10];
    int i;

    printf("Enter the elements of the array: ");
    for (i = 0; i<n; i++) //    for (i = 0; i<n; i++); the ";" is expected
    {
        scanf("%d", (a1 + i));
    }

    convert(a1, n, a2);

    printf("Output: ");

    for (i = 0; i<n; i++)
    printf("%d ", *(a2 + i));

    printf("\n");

    return 0;

}
void convert(int *a1, int n, int *a2)
{
    int *p;
    p = a1;
    while (p + n > a1 ) //this is true for loop on array
    {
        *a2 = ((*a1) + 6) % 10; //**a1 + 6 have fault 
        a1++;
        a2++;
        //p++;
    }
}

输入/输出:

Enter the length of the array: 5
Enter the elements of the array: 1
1
2
3
4
Output: 7 7 8 9 0
相关问题