thinkIn
V2EX  ›  问与答

[c 语言问题] 一次 for 循环后,指针所指内容完全丢失。不知原因是什么?有代码

  •  
  •   thinkIn · Apr 24, 2015 · 2760 views
    This topic created in 4063 days ago, the information mentioned may be changed or developed.
    int *p;
    int max;
    p=collect();//p获取正常
    max=p[0];
    for (int i=0;i<15;i++)
    max=(max>p[i+1])?max:p[i+1];
    while(max)
    {
    for (int i=0;i<16;i++)
    if(p[i]>=max) //最好不要用p[i]-max>=0,可能溢出
    printf(" * ");
    else printf(" ");
    printf("\n");
    max--;
    }

    第一次for循环后,p指向内容全变了,求教啊
    4 replies    2015-04-24 12:12:10 +08:00
    lifanxi
        1
    lifanxi  
       Apr 24, 2015
    不知道楼主的程序想干嘛。

    就看这段代码,没什么问题。

    但是代码里没有给出collect函数的实现,如果collect里的返回一个合理的数组的话,也是没问题的。但是如果collect里返回一个栈上的地址的话,那就呵呵了。
    thinkIn
        2
    thinkIn  
    OP
       Apr 24, 2015
    nt *collect(void)
    {
    int p[16]={0};
    ********
    return p;
    }

    应该就是一楼说的问题,thanks
    ledzep2
        3
    ledzep2  
       Apr 24, 2015
    楼上说的很对. 很可能是collect返回了一个本地数组, 也就是说是已经被释放掉的数组. 你需要返回一个malloc分别配内存. 然后用完之后手动释放掉.
    ilotuo
        4
    ilotuo  
       Apr 24, 2015
    int p 加个 static
    static int p[16];
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   968 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 19:55 · PVG 03:55 · LAX 12:55 · JFK 15:55
    ♥ Do have faith in what you're doing.