Thread: question about structure?

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    15

    question about structure?

    Anyone know why we can't use scanf to initialize strucutre?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    	struct automobile
    	{
    		char make[10];
    		char* model;
    		int number_of_doors;
    		float price;
    	}car;
    	 
    	scanf( "%s", car.model); /* can we do this? */
    	printf("%s", car.model);
    	
    	return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Well model is a pointer, you need to make it point somewhere.
    car.model = malloc( 10 );

    Then you can do as you suggest.

    Ideally, you should use fgets() for reading all input to prevent buffer overflows.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 12-14-2007, 03:34 PM
  2. Simple C# structure question
    By sketch in forum C# Programming
    Replies: 4
    Last Post: 09-14-2007, 04:29 PM
  3. data structure question
    By miami_victor in forum C++ Programming
    Replies: 13
    Last Post: 12-31-2004, 12:56 AM
  4. Array and Structure Question
    By loopshot in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2004, 05:10 PM
  5. structure question
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 12-03-2001, 09:04 PM