question about structure?

This is a discussion on question about structure? within the C Programming forums, part of the General Programming Boards category; Anyone know why we can't use scanf to initialize strucutre? Code: #include <stdio.h> #include <stdlib.h> int main() { struct automobile ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,544
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 12-14-2007, 02: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-30-2004, 11:56 PM
  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, 08:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21