【问题标题】:What can I do to input the value in char*?如何在 char* 中输入值?
【发布时间】:2020-10-16 00:02:06
【问题描述】:
typedef struct inventory
{
     char *name;
     int quantity;
} invent;

int main()
{
   invent *one=malloc(sizeof(invent));
   scanf("%s", one->name);
   ...
}

scanf() 不起作用。 还有其他方法吗? 我想如何在 char* 中输入值。

【问题讨论】:

  • 这能回答你的问题吗? using scanf function with pointers to character
  • 我试过invent.name=malloc(256);,但它不起作用。(错误:预期标识符或'(')
  • invent 不是对象,而是类型。你会想要one->name=malloc(256);。 (当然还要检查返回的指针对于两个 malloc 调用是否都不是 NULL
  • 我明白了。谢谢!
  • 你想在哪里存储字符串?

标签: c char-pointer


【解决方案1】:

您需要为name 成员进行第二次分配:

#define MAX_INPUT_LENGTH 20 // or however long your input needs to be
...
/**
 * Allocate space for the struct instance.
 */  
invent *one = malloc( sizeof *one );
if ( !one )
{
  fprintf( stderr, "memory allocation for one failed, exiting...\n" );
  exit( EXIT_FAILURE );
}

/**
 * At this point, one->name is uninitialized and doesn't point anywhere
 * meaningful.  Perform a second allocation to set aside space for the
 * input string itself.  Remember to account for the string terminator.
 */
one->name = malloc( sizeof *one->name * (MAX_INPUT_LENGTH + 1) ); 
if ( !one->name )
{
  fprintf( stderr, "memory allocation for one->name failed, exiting...\n" );
  exit( EXIT_FAILURE );
}

/**
 * At this point, we can store a string in one->name
 */
scanf( "%s", one->name );

完成后,按照分配的相反顺序解除分配:

free( one->name );
free( one );

【讨论】:

  • sizeof *one->name * 这里是表达乘以 1 的一种非常令人困惑的方式。完全没有必要。
  • 我会试试的。谢谢你的建议,约翰·博德!
  • @anatolyg:习惯的力量。不管目标类型如何,我总是使用sizeof *p * num_elements 成语,即使pchar *。这样我就不必担心类型之间的不匹配。眼睛刺痛略有增加,但它不止一次救了我的培根。
猜你喜欢
  • 2016-03-17
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
相关资源
最近更新 更多