assigning value to a char array in a structure

This is a discussion on assigning value to a char array in a structure within the C Programming forums, part of the General Programming Boards category; Hello, I am a first year student. I use gcc/netbeans to work with c. I have made a global structure ...

  1. #1
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20

    assigning value to a char array in a structure

    Hello, I am a first year student. I use gcc/netbeans to work with c. I have made a global structure then am trying to create another of that type that is an array.
    i am trying to fill the array->charname[] inside of a switch statement. I have tried all the reference material available to me and am lost and tied. I have totaly swithced directions and am considering using a function instead of switch, but fear I am over complicating a simple task. I hope this isn't rude, please forgive,
    here is my noodle mess:
    Code:
    /* 9B
    * File: main.c
    * Author: Clay
    *
    * Created on November 13, 2011, 7:29 PM
    */
    #include <stdio.h>
    #include <stdlib.h>
    #define MNAME 30
    #define MSTUD 50
    #define MGRADE 4
    struct NameGrade // Global structure NameGrade
       {
         char name[MNAME];
         int grade;
         struct NameGrade *nextstud;
       };
    int main() 
      { //Variables 
         char choice, entkey, cont; 
         int tempG, i, ct;
         char tempN[MNAME]; 
         struct NameGrade Student[MSTUD];
         typedef struct Student STU; 
    //ASK user for input
          printf("Enter your desired action below:\n"
         "A to create a linked list of names and grades.\n"
         "B to add a new student to the list.\n"
         "C to modify a student in the list\n"
         "D to delete a student from the list.\n"
         "E to display the list.\n"
         "F to EXIT this program.\n");
         scanf("%c", &choice);//USER enters choice from list
    //switch to execute USERS choice  temp disabled till I fix STU.name 
    //switch (choice) 
    //{Create an initial linked list of students and grades 
    // case 'A':
    // case 'a': 
           if(choice == "a"||"A")  //this IF is temporary till I figure
    //out why it isn't taking name
          while(cont != 'n' || 'N');
               {
                   i = 0;
                   printf("Enter Name: "); 
                   scanf("%s", &tempN);
                   Student->name[i] = tempN[i];
                   printf("Enter a grade for %s.\n", Student->name[i]); 
                   scanf("%d", &tempG);
                   printf("Continue entering names and grades?\n"
                   "Y for yes\n"
                   "N for no\n");
                   scanf("%c", &cont); 
                   i++;
                }
    /* break;           I have stopped here obviously***************
    
    //Insert a new student into the list
    case 'B':
    case 'b': 
    //
    break;
    //Modify an existing student in the list
    case 'C':
    case 'c': 
    //
    break;
    //delete an existing student from linked list
    case 'D':
    case 'd': 
    //
    break; 
    //Display the linked list done?
    case 'E':
    case 'e': 
    
    //ct = 0;used to count list entries
    for(i = 0; STU[i] != '\0'; i++)
    //ct++;
    printf(STU[i]);
    
    
    break; 
    //EXIT from the program
    case 'F':
    case 'f': 
    // exit;
    break;
    */
    return(0);
    }

  2. #2
    DRK
    DRK is offline
    Registered User
    Join Date
    Jun 2009
    Posts
    108
    1. Include this file
    Code:
    #include <string.h>
    2. Replace
    Code:
    Student->name[i] = tempN[i];
    printf("Enter a grade for %s.\n", Student->name[i]);
    with
    Code:
    strcpy(Student[i].name, tempN);
    printf("Enter a grade for %s.\n", Student[i].name);
    3. Replace
    Code:
    if(choice == "a"||"A")
    while(cont != 'n' || 'N');
    with
    Code:
    if(choice == 'a' || choice == 'A')
    while(i < MSTUD && cont != 'n' && cont != 'N')
    4. Initialize
    Code:
    i = 0; // move this instruction from while loop
    cont = '\0';
    before while loop.
    Last edited by DRK; 11-17-2011 at 02:27 AM.

  3. #3
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    Wow, huge difference. Thank you DRK. I did the changes and its working, except when it is supposed to scanf for cont, it jumps to enter name followed by grade. If I enter n for grade it exits succesfully. Any ideas?

  4. #4
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    Never mind... I moved the printf and scanf for cont after the i++ and it works great. Thank you VERY much once again.

  5. #5
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    Ok, I am trying to print the list now and can't figure out malloc. I believe I need to use malloc for Student however Student is not a ptr. This is what I have so far:

    Code:
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    #define MNAME 30
    #define MSTUD 50
    #define MGRADE 4
    #define TRUE 1
    #define FALSE 0
    int EXIT = FALSE;
    struct NameGrade  // Global structure NameGrade
          {
           char name[MNAME];
           int grade;
           struct NameGrade *nextstud;
          };
          
    int main()
    {
              //Variables        
             char choice, cont = '\0';    
             int tempG, i, ct;
             char tempN[MNAME];
      
    struct NameGrade Student[MSTUD];                     //here is my trouble
    Student[] = (int *) malloc(MSTUD * sizeof(int));
    if (Student == (int *) NULL)
        {
        printf("Failed to allocate Student structure array\n");
        exit(1);
        }

  6. #6
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    Ok, I am trying to print the list now and can't figure out malloc. I believe I need to use malloc for Student however Student is not a ptr. This is what I have so far:

    Code:
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    #define MNAME 30
    #define MSTUD 50
    #define MGRADE 4
    #define TRUE 1
    #define FALSE 0
    int EXIT = FALSE;
    struct NameGrade  // Global structure NameGrade
          {
           char name[MNAME];
           int grade;
           struct NameGrade *nextstud;
          };
          
    int main()
    {
              //Variables        
             char choice, cont = '\0';    
             int tempG, i, ct;
             char tempN[MNAME];
      
    struct NameGrade Student[MSTUD];                     //here is my trouble
    Student[] = (int *) malloc(MSTUD * sizeof(int));
    if (Student == (int *) NULL)
        {
        printf("Failed to allocate Student structure array\n");
        exit(1);
        }

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,593
    You should:
    • Indent your code properly.
    • Avoid global variables. (EXIT should probably be renamed and made a local variable.)
    • Decide whether you want NameGrade to be a node in a linked list or a separate structure.

    What I would do is write:
    Code:
    struct Student
    {
        char name[MNAME];
        int grade;
    };
    Now, if I want to have a singly linked list, I might also write:
    Code:
    struct StudentNode
    {
        struct Student student;
        struct StudentNode *next;
    };
    But if I want to have a dynamic array, I might write instead:
    Code:
    struct Student *students = malloc(MSTUD * sizeof(*students));
    (Though that begs the question of why MSTUD is a constant rather than a variable.)

    Remember to free what you malloc.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Oct 2011
    Location
    Denmark
    Posts
    80
    You don't need, and actually cannot use malloc unless you want to allocate memory to a pointer. But here you do :
    Code:
    struct NameGrade Student[MSTUD];
    Which means that you declare a statically allocated array of struct NameGrade, named Student with MSTUB size, and the memory is already allocated. And if you would use malloc, here is what you would do :
    Code:
    struct NameGrade *student = NULL;
    student = (struct NameGrade*)malloc(MSTUD * sizeof(struct NameGrade) );
    Note that I replaced your (int*) and (int) in the malloc, because the first one is to cast the return of the "malloc" (which even if not necessary is often clearer), and the second to give the size of the memory to allocate (here MSTUD times the size of the your structure).

    But I think here you want to do a linked list, so you should allocate the elements one by one in a loop and link them to each other.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,593
    Quote Originally Posted by Tibo-88
    Note that I replaced your (int*) and (int) in the malloc, because the first one is to cast the return of the "malloc" (which even if not necessary is often clearer)
    Unfortunately, because in C a function that is called before being declared is assumed to have a return type of int, such a cast can suppress a compile warning of a bug in which malloc is used without #include <stdlib.h>.

    Quote Originally Posted by Tibo-88
    and the second to give the size of the memory to allocate (here MSTUD times the size of the your structure).
    I suggest using sizeof(*student) instead of sizeof(struct NameGrade) because the former is guaranteed to be correct unless student is a pointer to void, in which case a compile error will be reported, whereas the latter might or might not be correct, so the reader has to check the declaration of student to be sure (e.g., in my example, a careless mistake might cause sizeof(struct StudentNode) instead of sizeof(struct Student) to be used, and a maintainer might not immediately spot the problem).
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Oct 2011
    Location
    Denmark
    Posts
    80
    Thank you laserlight for these information!
    I used this way because I think it is easier to understand the usage of malloc like that because the code tells you better what it is doing like : "I want a struct NameGrade pointer that will point to MSTUD struct NameGrade". At least that's how I learned it and I remember that I had a hard time with pointers, and that kind of stuff were helping.

    And I didn't know for the first part, but I remember having some "implicit declaration of malloc" warnings with everything working fine, is it because my compiler was smart enough to find it by itself?

  11. #11
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    So for dynamic MSTUD should be a variable. Just declare it as 'int MSTUD' and do not initialize it. I will give this a whirl. This is begining to get confusing and very exciting. Thank you LaserLight and Tibo-88.

  12. #12
    Registered User Clayg's Avatar
    Join Date
    Nov 2011
    Location
    Hawaii
    Posts
    20
    It worked great. Now that I created the list I am going to try to delete from the list and modify existing elements in the list.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assigning integer to char array.
    By SasDutta in forum C Programming
    Replies: 8
    Last Post: 06-23-2011, 03:25 AM
  2. Assigning structure elements to an array
    By anndruu12 in forum C Programming
    Replies: 14
    Last Post: 12-08-2010, 04:25 PM
  3. setting structure char array with string
    By Tom Bombadil in forum C Programming
    Replies: 6
    Last Post: 04-03-2009, 07:10 AM
  4. Assigning Const Char*s, Char*s, and Char[]s to wach other
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-29-2003, 10:52 PM
  5. Writing structure in a unsigned char array
    By nasir_sidd in forum C++ Programming
    Replies: 1
    Last Post: 12-10-2002, 03:09 AM

Tags for this Thread


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