Closed. This question is off-topic. It is not currently accepting answers. Learn more
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
三年前关闭。
我已经浏览了以前的帖子,我没有看到任何类似的我正在做的事情。我正试图将一个指针从函数传递回main。这是我所拥有的。。。
#include <stdio.h>
char* monthName ()
{
char month [20] = "January";
char* pMonth;
pMonth = month;
printf("Printing month from monthName function %s\n", month);
/*while (*pMonth != '\0')
  {
    putch(*pMonth);
    pMonth++;
  }*/
return pMonth;
}
int main (void)
{
char* monthName();
char* currentMonth;
currentMonth = monthName();
putch('\n');
while (*currentMonth != '\0')
  {
    putch(*currentMonth);
    currentMonth++;
  }
}

这是gdb输出
Breakpoint 1, monthName () at 132.c:4
4       char month [20] = "January";
(gdb) n
6       pMonth = month;
(gdb) n
7       printf("Printing month from monthName function %s\n", month);
(gdb) p pMonth
$7 = 0x61fee8 "January"
(gdb) n
Printing month from monthName function January
13      return pMonth;
(gdb) p pMonth
$8 = 0x61fee8 "January"
(gdb) n
14      }
(gdb) p pMonth
$9 = 0x61fee8 "January"
(gdb) n
main () at 132.c:20
20      putch('\n');
(gdb) p pMonth
No symbol "pMonth" in current context.
(gdb) q
A debugging session is active.

        Inferior 1 [process 7836] will be killed.

Quit anyway? (y or n) y
error return ../../gdb-7.6.1/gdb/windows-nat.c:1275 was 5

最佳答案

我认为你的问题可能是你返回了一个局部变量。一旦离开创建该变量的方法,并且堆栈增长到分配该变量的位置,则可以覆盖该变量。
相反,您应该查看malloc()free()以分配在离开方法后不会回收的持久内存。
一些文档:http://www.programiz.com/c-programming/c-dynamic-memory-allocation

关于c - 将指针从c中的函数传递回main,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37777676/

10-09 02:53