C - 使用 typedef 时如何从用户获取字符串?

标签 c pointers scanf fgets

我的代码中有以下 typedef:

typedef char * string;

我需要让用户输入一个字符串,以便我可以解析它并稍后使用内容。如果我只是用这个定义声明一个字符串,它就可以工作,如下所示:

string bob = "My name is bob!;
printf("%s\n", bob);

使用这个时我应该使用什么来获取用户输入,scanf() 和 fgets() 当我尝试使用它们时,两者都会出现段错误(核心转储)错误。

这是为了学校,这就是为什么我需要以这种方式使用 typedef。

最佳答案

您可以typedef一个指针变量,但在使用或访问该typedefed指针变量时必须小心,因为通常您不会看到声明定义中的*符号可能位于其他地方,您可以将其视为普通变量。

如果您想首先从运行时或文件中获取指针变量的输入,您应该分配内存。

int main()
    {
            typedef char * string;// now string also a char pointer
            string bob;// bob is pointer variable
            printf("enter the string\n");
            scanf("%s",bob);//bob is uninitialized pointer .. u can't put any data
            printf("%s\n", bob);
          //once job is done free dynamically allocated memory using free function 
    }

上面的代码会导致段错误,所以先动态分配内存。

        string bob;
        bob = malloc(SIZE);//how much memory you want , mention in SIZE variable.
        printf("enter the string\n");
        scanf("%s",bob);
        printf("%s\n", bob);

关于C - 使用 typedef 时如何从用户获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47337696/

相关文章:

c - 在 Windows 中检测 VPN 连接?

c - 在 fopen() 之后使用 stat() 来避免 TOCTOU 问题?

计算未初始化字符数组的长度

c++ - 我的构造函数主体中的简单指针语法问题

c - (C) 扫描后比较 long long 数组的两个元素不起作用

c - 如何在C中输入n个字符串(n由用户输入)而不分配n个空格?

C 尝试检查无效输入

c - 修复 FANN 随机生成器的种子 - C

c - 在 C 中取消引用本地数组

c - WinSDK 7.1 : Getting Started with the Windows SDK Tools for Native Windows app development?