Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

arrays - Why does the program display warning passing argument 1 of 'circularswap' makes pointer from integer without a cast?

I am working on this problem:

Given an array p[5], write a function to shift it circularly left by two positions. Thus, if p[0] = 15, p[1]= 30, p[2] = 28, p[3]= 19 and p[4] = 61 then after the shift p[0] = 28, p[1] = 19, p[2] = 61, p[3] = 15 and p[4] = 30. Call this function for a (4 x 5 ) matrix and get its rows left shifted.

Here's the code I tried:

    #include <stdio.h>
    
#include <stdio.h>
void circularswap(int arr[][5],int n,int m){ int arr1[n][m],i,j;
    for (i=0;i<n;i++){
        for (j=0;j<m;j++){
            arr1[i][j]=*(*(arr+i)+j);
        }
    }
    for (i=0;i<m;i++){
        *(*(arr+i)+0)=arr1[i][2];
        *(*(arr+i)+1)=arr1[i][3];
        *(*(arr+i)+2)=arr1[i][4];
        *(*(arr+i)+3)=arr1[i][0];
        *(*(arr+i)+4)=arr1[i][1];
    }
        for (i=0;i<4;i++){
        for (j=0;j<5;j++){
            printf ("%d",arr[i][j]);
        }
        printf ("
");
    }
}
int main(){ int i,j;
    int arr[4][5]={(15,30,28,19,61),(15,30,28,19,61),(15,30,28,19,61),(15,30,28,19,61)};
    circularswap((arr,4,5));
    return 0;
}

Unfortunately, this shows up warnings. Can someone please tell why the warnings pop up and how to remove them?

question from:https://stackoverflow.com/questions/65880514/why-does-the-program-display-warning-passing-argument-1-of-circularswap-makes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to many parentheses when calling the function.

The expression (arr,4,5) is using the comma operator and will evaluate all the sub-expressions in the list, but return only the 5.

I.e. your call is really the same as circularswap(5), which is incorrect in multiple ways.

To solve your problem drop the inner parentheses:

circularswap(arr,4,5);

You have a similar problem when initializing your array: You use parentheses () instead of curly braces {}.

So the array definition is really equal to:

int arr[4][5]={ { 61 }, { 61 }, { 61 }, { 61 } };

[Note how I use curly-braces in the example above]


On another note, for any pointer p and index i, the expression *(p + i) is exactly equal to p[i]. The latter is easier to read and understand, and also less to write.

It matters especially when using arrays of arrays like you do, where e.g. *(*(arr+i)+0) could be replaced with arr[i][0].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...