【问题标题】:Pint all the odd numbers between 2 numbers using pointer and array [closed]使用指针和数组标出两个数字之间的所有奇数[关闭]
【发布时间】:2019-08-17 07:34:41
【问题描述】:

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

如果 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]);
}

【问题讨论】:

  • 查找“如何从 C 中的函数返回数组”。
  • 还记得用您的语言名称(在本例中为 c)和版本(例如 [c11])标记问题
  • 问题中的代码不可能是你正在运行的代码!
  • \\ 这不是单行 cmets 表示法。应该是//

标签: c segmentation-fault


【解决方案1】:

这样做

return(&t[0]); /* here you are returning address of locally created array, its scope is within this function only */

您的程序导致未定义的行为,因为您正在从一个函数返回本地创建的数组变量的地址,因为它的范围在这个函数之内而不是外部。你的编译器应该这样警告你

错误:函数返回局部变量的地址 [-Werror=return-local-addr]

如果您可以使用类似的标志进行编译

gcc -Wall -Wextra -pedantic -Werror test.c

【讨论】:

  • 所以我必须创建动态内存来传递数组?
  • 是的,您可以通过创建动态数组并将其返回到main() 并在使用完成后释放动态指针来实现。另一种方法是在函数参数本身中传递缓冲区及其长度,例如 odd(l,k,t, numOfEle);
猜你喜欢
  • 2015-11-13
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 2010-09-19
相关资源
最近更新 更多