我不知道代码出了什么问题,但出现了段错误。
如果 l=2 且 k= 5,则输出应为 3 5
#include<stdio.h>
int* odd(int,int,int*);
int main()
{
int l,k,*count;
int o;
o=0;
printf("enter l and k");\\entering the lest and right limit\\
scanf("%d%d",&l,&k);
count= odd(l,k,&o);\\passing address of o so i can get the count of
loop using pointer\\
for(int j=0;j<=(o);j++)
printf("%d",*(count +j));
}
int* odd(int l,int k,int * o)
{
int t[10],m=0;
for(int i=l;i<=k;i++)
{
if(i/2!=0)
{
t[m]=i;
m++;
}
}
*o=m;(using pointer to get count of loop)
return(&t[0]);
}
最佳答案
通过这样做
return(&t[0]); /* here you are returning address of locally created array, its scope is within this function only */
当您从函数返回本地创建的数组变量的地址时,您的程序会导致未定义的行为,因为它的作用域位于该函数内而不是外部。你的编译器应该这样警告你
error: function returns address of local variable [-Werror=return-local-addr]
如果你可以使用像这样的标志进行编译
gcc -Wall -Wextra -pedantic -Werror test.c
关于c - 使用指针和数组打印 2 个数字之间的所有奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534263/