我的代码中有以下 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/