-1
typedef struct inventory
{
     char *name;
     int quantity;
} invent;

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

scanf() doesn't work. Is there any other way? I want how to input the value in char*.

1 Answers1

0

You need to do a second allocation for the name member:

#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 );

When you're finished, you deallocate in the reverse order you allocated:

free( one->name );
free( one );
John Bode
  • 119,563
  • 19
  • 122
  • 198
  • `sizeof *one->name *` here is a very confusing way to express multiplication by 1. Completely unnecessary. – anatolyg Jun 25 '20 at 14:05
  • I'll try. Thank you for your advice, John Bode! – erehwyrevemai Jun 25 '20 at 14:19
  • @anatolyg: Force of habit. Regardless of the target type, I always use the `sizeof *p * num_elements` idiom, even if `p` is `char *`. That way I never have to worry about mismatches between types. There is a slight increase in eye-stabbiness, but it's saved my bacon more than once. – John Bode Jun 25 '20 at 15:32