c-传递到函数后给出随机值的指针


#include<stdio.h>
#include <stdlib.h>
void  deal_queries(int *arr, int limit, int numQueries, int filled) {
// Write your code here
for(int i=0;i<filled;i++)
{
printf("%d ",*(arr+0));
}
}
int * read_input(int N,int n){
//declare dynamic array of size N
// take input n integers and store them in the array and return pointer to this
int i;
int *ptr;
int array[N];
ptr=array;
for(i=0;i<n;i++)
{scanf("%d ",ptr);ptr++;}
ptr=array;
return (ptr);
}
int main()
{
int N,Q,n; 
scanf("%d %d %d",&N,&Q,&n);
int* arr=read_input(N,n);
printf("%d ",*(arr+0));
deal_queries(arr,N,Q,n);
return 0;
}

当我在主函数中打印arr元素时,我得到了正确的值,但如果我把它们传递到处理查询函数中,我得到的是随机值,有人能解释为什么会发生这种情况吗?

变量arrayread_input的本地变量,因此当从函数返回并在此之后访问它时,它的生命周期将结束,这是非法的。

相反,您应该在堆上分配一个数组并使用它。

#include<stdio.h>
#include <stdlib.h>
void  deal_queries(int *arr, int limit, int numQueries, int filled) {
// Write your code here
for(int i=0;i<filled;i++)
{
printf("%d ",*(arr+0));
}
}
int * read_input(int N,int n){
//declare dynamic array of size N
// take input n integers and store them in the array and return pointer to this
int i;
int *ptr;
int *array=malloc(sizeof(*array)*N); /* allocate an array on the heap */
if(array==NULL) return NULL; /* check if allocation succeeded */
ptr=array;
for(i=0;i<n;i++)
{scanf("%d ",ptr);ptr++;}
ptr=array;
return (ptr);
}
int main()
{
int N,Q,n; 
scanf("%d %d %d",&N,&Q,&n);
int* arr=read_input(N,n);
if(arr==NULL) return 1; /* check if allocation succeeded */
printf("%d ",*(arr+0));
deal_queries(arr,N,Q,n);
free(arr); /* free allocated array */
return 0;
}

返回指向本地自动存储变量的指针,该变量在函数返回时停止存在,即UB。

int array[N];
ptr=array;
for(i=0;i<n;i++)
{scanf("%d ",ptr);ptr++;}
ptr=array;
return (ptr);

你需要使其静态(坏的方式(或动态分配内存

static int array[N];
ptr=array;

或更好的

//int array[N];
ptr=malloc(sizeof(*ptr)*N);

错误在read_input中,您有:

int array[N];
ptr=array;
return (ptr);

变量array是函数中的局部变量。对ptr的赋值使它指向这个局部数组的第一个元素。一旦函数返回并且array的寿命结束,此指针将变为无效。

您需要使用malloc来动态分配阵列:

int *array = malloc(N * sizeof *array);
int *ptr = array;
// Fill array using the ptr variable...
return array;

指针不是问题,它指向的是什么

int * read_input(int N,int n) {
...
int array[N]; // This array is in automatic memory,
ptr=array;    // so it is valid only inside read_input
...
return (ptr); // you are returning a pointer to it
}

为了做你想做的事情,你需要使用malloc:

int* ptr = malloc(sizeof(int)*N);

在循环中使用另一个指针,或对ptr应用索引,如下所示:

for (i = 0 ; i < n ; i++) {
scanf("%d ", &ptr[i]);
}

最新更新