【问题标题】:Could not get the entered string from the stack of function [duplicate]无法从函数堆栈中获取输入的字符串[重复]
【发布时间】:2018-02-23 02:03:57
【问题描述】:
#include <stdio.h>

#include <stdlib.h>

static void get_string(char *ac)
{
    ac = (char *)malloc (1 * sizeof (char));
    printf("Enter the string to count vowels and consonants in a string using pointers: ");
    scanf("%s", ac);
}

main(int argc, char *argv[])
{
    char *ac = NULL;
    get_string(ac);
    printf("The Entered string is:%s", ac);
    for(;;);
}

无法从函数堆栈中获取输入的字符串。返回 null。谁能帮我调试一下?

【问题讨论】:

  • 如果你只为 1 个字符分配空间,你希望得到什么字符串?

标签: c pass-by-value function-call


【解决方案1】:

C 中的函数参数是按值传递的。从被调用函数内部对参数所做的任何更改都不会反映到函数调用时提供的实际参数。

在您的情况下,您想要更改ac 本身(而不是它指向的内存位置的内容),因此,这需要一个指向ac 的指针。

也就是说,

【讨论】:

  • 那我需要在代码中做哪些修改?
  • 为您的输入分配一个合理的长度(例如 256),在您的 scanf() 格式字符串中使用 [length-1] 的宽度,然后从 get_string() 返回字符串一个 char* 或使用双指针参数/参数以允许将分配的指针传回给调用者。最容易退货。
  • 哦 - 在 main() 中打印后释放 char*。
  • ..或更改您的设计,以便 main() 分配字符串空间并 'get_string()' 加载它。在这种情况下,可能应该传入字符串指针和最大长度。
  • @MartinJames 我会排在最后一个想法,最干净的,恕我直言。
猜你喜欢
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 2015-08-28
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2021-11-23
相关资源
最近更新 更多