Thread: Structures

  1. #1
    Registered User
    Join Date
    Apr 2015
    Posts
    69

    Structures

    Hello,

    please help me in the below code is it not possible to initialize 100 to P.

    Code:
    #include <stdio.h>
    struct book
    {
    int a;
    float b;	
    } *ptr, p=100;
    int main(){
    	ptr = &p;
    	printf ("Eneter an integer");
    	scanf ("%d", &(*ptr).a);
    	printf ("Enter a float");
    	scanf ("%f", &(*ptr).b);
    	printf ("Display ");
    	printf("%d\n", (*ptr).a);
    	printf ("%f\n", (*ptr).b);
    	return 0;
    }

  2. #2
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    You've defined a structure, struct book, with two members. Member a is an integer, and member b is a float.

    If you define a variable p of that structure type, what do you mean by initializing it to 100?

  3. #3
    Registered User
    Join Date
    Apr 2015
    Posts
    69
    i would like to multiply integer with 100, by initializing p with 100.
    Last edited by Shankar k; 09-20-2015 at 09:52 PM.

  4. #4
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Eh? p is a structure, not a number. If you want to initialize a structure, you need to define the values its members should be initialized to. (If you initialize at least one member its value, the rest get initialized too, to zero, say the C standards.) It is like I was asking your first and last name, and you answered, "100". Makes no sense.

    Also, your code does not do any kind of multiplication, and initialization is not going to change that in any way.

  5. #5
    Registered User FourAngels's Avatar
    Join Date
    Aug 2015
    Location
    Canada
    Posts
    130
    I wrote this sample code using your structure, however I do not know what you actually want to do with the program but it looks like you want a 100 books on record.
    Code:
    #include <stdio.h>
    #include<stdlib.h>
    
    struct book
    {
    int a;
    float b;
    };
    
    int main(){
        struct book books[100];
        struct book * bookcopy;
    
    
        printf ("Enter an integer: ");
        scanf ("%d", &books[0].a);
        printf ("Enter a float: ");
        scanf ("%f", &books[0].b);
    
        printf ("Display %d and %f\n", books[0].a, books[0].b);
    
        bookcopy = (struct book *) malloc(sizeof(struct book));
        if (bookcopy == NULL) printf("Dynamic Memory error.\n");
    
        bookcopy->a = books[0].a;
        bookcopy->b = books[0].b;
    
    
        printf("Copy %d and %f\n", bookcopy->a, bookcopy->b);
    
        free(bookcopy);
    
        return 0;
    }
    One of the problems with an array is that all of the data is uninitialized. I ran the program and entered only one record, but the other records are filled with junk. Here is what the first five records contain, my input is 11 for the integer and 5.4 for the float. It looks like if someone accessed books[1].a, the variable would hold the number -8921.
    Code:
    $3 = {{a = 11, b = 5.4000001}, {a = -8921, b = 4.59163468e-41}, {a = 0, b = 0}, {a = -134224672, 
        b = 4.59163468e-41}, {a = -9280, b = 4.59163468e-41}}
    Last edited by FourAngels; 09-20-2015 at 11:47 PM.

  6. #6
    Registered User
    Join Date
    Apr 2015
    Posts
    69
    Thank you.

  7. #7
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    850
    1: No cast is needed, nor recommended of the return type from malloc().

    One of the problems with an array is that all of the data is uninitialized.
    2. Initialize the first element of the array, and the remainder of the elements, the members of the structs in this case, are initialized to 0, for ints, 0.0 for floats, and NULL for pointers. Please see my version of your code, printing out the first 5 elements of the array.
    Code:
    #include <stdio.h>
    #include<stdlib.h>
    
    struct book
    {
       int a;
       float b;
    };
    
    int main(){
       struct book books[100]= {{0, 0.0}};
       struct book * bookcopy = NULL;
       int x = 0;
    
       printf ("Enter an integer: ");
       scanf ("%d", &books[0].a);
       printf ("Enter a float: ");
       scanf ("%f", &books[0].b);
    
       for(x = 0; x < 5; x++)
       {
          printf ("Display %d and %f\n", books[x].a, books[x].b);
       }
    
       bookcopy = malloc(sizeof(struct book)); // Don't cast malloc() return!
       if (bookcopy == NULL) printf("Dynamic Memory error.\n");
    
       bookcopy->a = books[0].a;
       bookcopy->b = books[0].b;
    
    
       printf("Copy %d and %f\n", bookcopy->a, bookcopy->b);
    
       free(bookcopy);
    
       return 0;
    }

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,345
    A few other things to note concerning FourAngels' sample code from post #5 and rstanley's version thereof from post #7:
    • Check the return value of scanf. The user could enter invalid input, in which case you would want to respond to it instead of proceeding as if the user entered valid input.
    • Instead of this:
      Code:
      bookcopy = malloc(sizeof(struct book));
      write:
      Code:
      bookcopy = malloc(sizeof(*bookcopy));
      This works regardless of the type of bookcopy, except in the special case where bookcopy is a pointer to void (in which case you wouldn't be able to write bookcopy->a and get away with it).
    • Having checked if malloc returned a null pointer, you should not only print an error message, but also make it such that the code that depends on malloc returning a non-null pointer does not run.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User FourAngels's Avatar
    Join Date
    Aug 2015
    Location
    Canada
    Posts
    130
    I didn't want to do the cast on the return type however the compiler complained, but it might be because I wrote c code and compiled it with the g++ compiler instead of the regular gcc compiler because I used the same open project in qt creator which happened to be a c++ project. It looks nicer without the cast.

    Yes, I did remember something about initializing the values of arrays, it is better to do it that way. I actually forgot how to write an initialization list in c, but I did write a linked list for this code, and I think that I did it okay?...again, it was compiled with g++ so the malloc still has a cast in this code.
    Code:
    #include <stdio.h>
    #include<stdlib.h>
    
    struct book {
        int a;
        float b;
        struct book *next = NULL;
    };
    
    void getBookList (struct book* node, int size) {
        int n = 0;
        float f = 0.2;
    
        while(size-- > 0) {
            node->next = (struct book *) malloc(sizeof(struct book));
            node->b = f+ size;
            node->a = n++;
            node = node->next;
        }
    
    }
    
    void printList ( struct book*node, int size){
        while (size-- > 0) {
            printf("List %d, int: %d, float: %f\n", size, node->a, node->b);
            node = node->next;
        }
    }
    
    void freeList (struct book *node, int size) {
        struct book *head = node->next;
        while (size-- > 0){
            free(node);
            node = head;
            head = head->next;
        }
    }
    
    int main(){
    
        struct book * book_list = (struct book *) malloc(sizeof(struct book));
    
        getBookList(book_list, 3);
    
        printList (book_list, 3);
        freeList (book_list, 3);
        free(book_list);
    
        return 0;
    }

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,345
    Quote Originally Posted by FourAngels
    I didn't want to do the cast on the return type however the compiler complained, but it might be because I wrote c code and compiled it with the g++ compiler instead of the regular gcc compiler because I used the same open project in qt creator which happened to be a c++ project.
    Compile C code with a C compiler; compile C++ code with a C++ compiler.

    Quote Originally Posted by FourAngels
    Yes, I did remember something about initializing the values of arrays, it is better to do it that way. I actually forgot how to write an initialization list in c, but I did write a linked list for this code, and I think that I did it okay?...again, it was compiled with g++ so the malloc still has a cast in this code.
    Your code is invalid C and your C compiler would have told you why. Compile C code with a C compiler; compile C++ code with a C++ compiler. If you refuse to do so, suspend helping on the C programming forum until you have reached such expertise in C that you do not need to check your valid C code with a C compiler to be sure that it is valid.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User FourAngels's Avatar
    Join Date
    Aug 2015
    Location
    Canada
    Posts
    130
    Okay, okay, take it easy. I wrote the linked lists last night and I did not realize that I compiled with g++ instead of gcc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Tree Structures Best Structures!!! Discuss.
    By MutantJohn in forum General Discussions
    Replies: 20
    Last Post: 09-07-2013, 01:17 AM
  2. Link Lists of Structures within Structures...
    By Zocheyado in forum C Programming
    Replies: 3
    Last Post: 04-17-2012, 04:21 PM
  3. Problems with Nested Structures and Arrays of Structures
    By Ignoramus in forum C Programming
    Replies: 4
    Last Post: 03-02-2010, 01:24 AM
  4. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-05-2006, 11:06 PM
  5. Replies: 5
    Last Post: 04-11-2002, 11:29 AM