c - 使用指针和数组打印 2 个数字之间的所有奇数

标签 c segmentation-fault

我不知道代码出了什么问题,但出现了段错误。

如果 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/

相关文章:

(u)intmax_t 可以保存一个函数指针吗?

C++ 段错误 : 11

android - 运行 Pocketsphinx 演示项目时出现问题,段错误?

c++ - 游戏的跨平台声音 API?

c - 如何从虚拟机在azure中写入启动诊断中的串行日志?

c - 为什么这段代码中每个 printf 的输出不同?

c - 段错误(核心转储)字符数组

c - while(fgets) 之后的 memset()

python-3.x - opencv python3 中 imshow 的段错误

c++ - C++ 列表中的段错误