为什么我不能通过C代码制作这个系列?

时间:2017-11-08 18:46:24

标签: c function series

你能告诉我为什么这不起作用。

int function(int);

int main()
{
    int g[20],N;
    printf("Type N");
    scanf("%d",&N);
    g[20]=function(N);
    printf("s[0] is %d\n",g[0]);
    printf("s[1] is %d\n",g[1]);
    printf("s[2] is %d\n",g[2]);

}

int function(int N){
   int s[20];
s[0]=1;
s[1]=3;
s[2]=5;

return s[20];
}

我只是希望我的函数返回这个数字1,3,5,但它返回一些奇怪的数字,我认为它的地址或其他东西。 PS。我刚开始学习C。

2 个答案:

答案 0 :(得分:0)

你需要这样的事情。

void function(int *);

int main()
{
    int g[20],N;                  // array g local to main funciton
    printf("Type N");
    scanf("%d",&N);
    function(g);            // invoke function by passing array base address as an argument
    printf("s[0] is %d\n",g[0]);   // the first three positions of the g array
    printf("s[1] is %d\n",g[1]);  // have not been set by function
    printf("s[2] is %d\n",g[2]);  // they are also all unknown values

}

void function(int *s){ 
    s[0]=1;       //*(s+0)      
    s[1]=3;     
    s[2]=5;

}

答案 1 :(得分:-2)

从您的代码中,您似乎对数组和范围有一些误解。您声明的两个数组以未知值开始,直到您设置它们为止。看到我对原始代码的评论:

int function(int);

int main()
{
    int g[20],N;                  // array g local to main funciton
    printf("Type N");
    scanf("%d",&N);
    g[20]=function(N);            // invoke function with int typed in and return int
    printf("s[0] is %d\n",g[0])   // the first three positions of the g array
    printf("s[1] is %d\n",g[1]);  // have not been set by function
    printf("s[2] is %d\n",g[2]);  // they are also all unknown values

}

int function(int N){ // you never use N in this function, why is it a parameter
   int s[20];        // declare a int array local to function
s[0]=1;              // you only set the first three items in array, rest are unknown values.
s[1]=3;
s[2]=5;

return s[20]; // return the 20th int item of the array, (unknown memory contents)
}