Thread: pointers in array and other questions

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    30

    pointers in array and other questions

    hello guys,

    1st question:

    lets say i have
    Code:
    array[10]
    and every variable (
    Code:
    array[i]
    ) is a pointer towards a
    Code:
    struct str{}
    ;

    is this sentence correct?
    e.g.
    Code:
    array[3]=&str;
    should i initialize every variable to a letter(lets say letter "a") ,looking smt like this:

    pointers in array and other questions-12084178_1282667038425695_1552890293_n-jpg
    ?

    2nd question:
    the array should be declared this way:

    Code:
    char array[10];
    (if i choose to use the letters as variables-pointers)

    or this way :

    Code:
    char *array[10]

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    For your first question: it is a bit hard to see when you don't have declarations to refer to, so allow me to create my own example. Suppose you have a struct type declared like this:
    Code:
    struct X
    {
        int n;
    };
    Then you have an array of pointers to objects of that struct type:
    Code:
    struct X *xs[10];
    Then you declare an object of that struct type:
    Code:
    struct X x;
    You can then take the address of that object and assign it to one of the elements of the array:
    Code:
    xs[3] = &x;
    For your second question: it depends on what you want to do.
    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

  3. #3
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    let 's assume i initialize every pointer of the array towards the structure.

    1st question:
    how can i access the structure?

    2nd q:
    the direction(the pointers in the array) will be the same?
    i mean , if i access the structure through the pointer xs[1] and change something in the structure, then the pointer xs[0] will also lead to that changed struct...or will it lead to the initial struct?

  4. #4
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    also

    will i have to check if there is any memory left in the array after enter the elements of the struct?

    i believe not but i am prettty confused right now

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by George Ioannou
    let 's assume i initialize every pointer of the array towards the structure.

    1st question:
    how can i access the structure?
    xs is an array of pointers to struct objects. Hence, xs[i] is a pointer to a struct object, thus *xs[i] is a struct object. More commonly you would write xs[i]->n to access the member named n.

    Quote Originally Posted by George Ioannou
    2nd q:
    the direction(the pointers in the array) will be the same?
    i mean , if i access the structure through the pointer xs[1] and change something in the structure, then the pointer xs[0] will also lead to that changed struct...or will it lead to the initial struct?
    This depends on how you assign to the pointers. If the pointers point to the same struct object, then of course modifying that struct object through any of the pointers will modify it for all of the pointers. If they point to different struct objects, then of course modifying one struct object through the corresponding pointer will have no effect on any of the other struct objects.

    EDIT:
    Quote Originally Posted by George Ioannou
    will i have to check if there is any memory left in the array after enter the elements of the struct?

    i believe not but i am prettty confused right now
    I suggest that you work with an array of struct objects first:
    Code:
    struct X xs[10];
    Only after you are familiar with this should you go on to try your hand with an array of pointers.
    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

  6. #6
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    http://im.cprogramming.com/images/misc/quote_icon.png Originally Posted by George Ioannou
    2nd q:
    the direction(the pointers in the array) will be the same?
    i mean , if i access the structure through the pointer xs[1] and change something in the structure, then the pointer xs[0] will also lead to that changed struct...or will it lead to the initial struct?



    This depends on how you assign to the pointers. If the pointers point to the same struct object, then of course modifying that struct object through any of the pointers will modify it for all of the pointers. If they point to different struct objects, then of course modifying one struct object through the corresponding pointer will have no effect on any of the other struct objects.





    so the pointers will point towards "n" and not towards the structure as a whole?

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by George Ioannou
    so the pointers will point towards "n" and not towards the structure as a whole?
    No, read the original array declaration again:
    Code:
    struct X *xs[10];
    xs is an array of pointers to struct X objects. Therefore, for a given valid index i, xs[i] is a pointer to a struct X object. A pointer to a struct X object, not a pointer to the member named n. If you do not understand this, then you should first familiarise yourself with structures and pointers before moving on to arrays of pointers to struct objects.
    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

  8. #8
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    ok i got it ,i missunderstood something you wrote.

    if i didn't knew the size of the array in the first place.

    can i use double pointers?

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by George Ioannou
    if i didn't knew the size of the array in the first place.

    can i use double pointers?
    Yes, but... I recommend that you work with a pointer first, e.g.,
    Code:
    struct X *xs = malloc(sizeof(*xs) * N);
    where N is the number of elements that you wish to allocate.
    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

  10. #10
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    ok understood...i'm currently working on a project so i might hit you with some questions again later thanks for your time!

  11. #11
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    so...after much reading on pointers and what has been written above,double pointers etc. i still find it pretty hard to grasp the whole idea of the concept so i give you a part of my assignment and the code i have written up until now:

    Part of the assignment:
    The program must start by asking the user what is the maximum number of rentals he would like to manage.An array must be initialized then , which contains variables that are pointers to a structure called Rental.During the input of a new rental-basically the objects of the structure- , you should check wether there is still enough available in the array and if there is any the new rental will be inputed

    this is the code i have written so far:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    #define LICENCE_PLATE_LENGTH 7 //defines that i need to use in other parts of the assignment
    #define LICENCE_PLATE_ALPHA_LENGTH 3
    #define LICENCE_PLATE_NUM_LENGTH 4
    
    
    void licence_plate_input(void), client_name_input(void); // functions for other parts too
    
    
    typedef struct Rental // Struct given to us by lecturer
    {
        int nDays;
        float kmsDriven;
        char carLicencePlate[LICENCE_PLATE_LENGTH+1];
        char *clientName;
        char licence_plate;
        char chargingCategory;
    }rentals;
    
    
    int main()
    {
        int  max_number, code, counter ;
        rentals  **ptr=NULL; // problem no1.
    
    
        printf("Welcome to the Car Rental Charging System!\n\n");
        printf("Welcome to the Car Rental Manager!\n");
        printf("How many rentals do you plan to manage?");
        scanf("%d", &max_number);
    
    
        ptr= (Rental **)malloc(max_number*sizeof(rentals)); //problem no2.
        if (ptr==NULL)
        {
            printf("\n\nMemory allocation error.");
            return 1;
        }
        do
        {
            printf("Program menu-Please select one of the following options:\n");
            printf(" 1. Insert new rental\n");
            printf(" 2. Delete rental\n");
            printf(" 3. Show rentals\n");
            printf(" 4. Terminate program\n");
            scanf("%d", &code);
            switch (code)
            {
                case 1:
                    printf("\nGive licence plate of rented car: ");
                    licence_plate_input();
                    printf("\nGive name of client that made the rental: ");
                    client_name_input();
                    printf("\nGive days of rental:");
                    scanf("%d", &max_number);
                    for (counter=0; counter<max_number; counter++)
                    {
                        ptr[counter]=(Rental *)malloc(sizeof(rentals))// problem no3.
                    }
                case 2:// other parts of the assignment
                case 3:// ...
                case 4: break;
            }
        }
        while (code!=4)
    
    
    }

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This is a little wrong:
    Code:
    typedef struct Rental // Struct given to us by lecturer
    {
        int nDays;
        float kmsDriven;
        char carLicencePlate[LICENCE_PLATE_LENGTH+1];
        char *clientName;
        char licence_plate;
        char chargingCategory;
    }rentals;
    It is wrong because it declares a struct that you can refer to either as struct Rental or as rentals. Calling it "rentals" is a bit odd: it represents the rental of a single car. As subsequent code shows, you want to refer to the struct as Rental. Therefore, you should have written:
    Code:
    typedef struct // Struct given to us by lecturer
    {
        int nDays;
        float kmsDriven;
        char carLicencePlate[LICENCE_PLATE_LENGTH+1];
        char *clientName;
        char licence_plate;
        char chargingCategory;
    } Rental;
    Consequently, instead of this:
    Code:
    rentals  **ptr=NULL;
    you probably want:
    Code:
    Rental **rentals = NULL;
    This is much better: "ptr" does not give any hint as to what the pointer is for, whereas "rentals" describes that the pointer is for a dynamic array of pointers to Rental objects.

    Next, this is wrong:
    Code:
    ptr= (Rental **)malloc(max_number*sizeof(rentals));
    It should be:
    Code:
    rentals = malloc(max_number * sizeof(rentals[0]));
    Notice the sizeof(rentals[0]): this ensures that you allocate max_number elements of the array, not max_number of some other thing, which is the mistake you made by writing sizeof(rentals) (which is now equivalent to sizef(Rental)).

    Of course, now you have a dynamic array of pointers, but you do not actually have any space for any Rental object. Hence, later when you want to create the objects, it should be:
    Code:
    rentals[counter] = malloc(sizeof(*rentals[counter]));
    You could have written equivalently:
    Code:
    rentals[counter] = malloc(sizeof(Rental));
    and in a way this is simpler, but my suggested version is better because it avoids the making of a mistake with the type used for the sizeof.

    Remember to free what you malloc.
    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

  13. #13
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    wow this tips are really usefull helped me understand even more...thanks a lot!!

  14. #14
    Registered User
    Join Date
    Nov 2015
    Posts
    30
    update: after working on the project i wrote this code
    :

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    #define LICENSE_PLATE_LENGTH 7
    #define LICENSE_PLATE_ALPHA_LENGTH 3
    #define LICENSE_PLATE_NUM_LENGTH 4
    
    typedef struct {
     int nDays;
     float kmsDriven;
     char carLicensePlate[LICENSE_PLATE_LENGTH+1];
     char *clientName;
     char chargingCategory;
    } Rental;
    
    void licence_plate_enter(Rental** rental, int counter);
    
    int main()
    {
        int counter,choice,max_number;
        Rental** rentals=NULL;
        char del_number, del_name, show_number, show_name;
    
    
        printf("Welcome to the Car Rental Charging System!\n\n");
        printf("Welcome to the Car Rental Manager!\n");
        printf("How many rentals do you plan to manage? ");
        do
        {
           scanf("%d", &max_number);
           if (max_number<0)
           {
               printf("\nInvalid number.");
               printf("\nHow many rentals do you plan to manage?");
           }
        }
        while (max_number<0);
    
    
    
    
        rentals=(Rental **)malloc(max_number * sizeof(Rental));
        if (rentals==NULL)
        {
            printf("\nRentals could not be stored");
            return 1;
        }
        for (counter=0; counter<max_number; counter++)
        {
            rentals[counter]=(Rental *)malloc(sizeof(Rental));
            if (rentals[counter]==NULL)
            {
                printf("\nRentals could not be stored");
                return 1;
            }
        }
        counter=0;
        do
        {
            printf("\nProgram menu - Please select one of the following options:\n");
            printf("1. Insert new rental\n");
            printf("2. Delete rental\n");
            printf("3. Show rentals\n");
            printf("4. Terminate program\n");
            scanf("%d", &choice);
            switch(choice)
            {
                case 1:
                    printf("Give license plate of rented car: ");
                    licence_plate_enter(rentals, counter);
    
    
    
    
                    printf("Give name of client that made the rental: ");
                    rentals[counter]->clientName=(char *)malloc(100*sizeof(char));
                    gets(rentals[counter]->clientName);//synarthsh
    
    
                    printf("Give days of rental: ");
                    scanf("%d", &rentals[counter]->nDays);
    
    
                    printf("Give kilometers driven: ");
                    scanf("%f", &rentals[counter]->kmsDriven);
    
    
                    printf("Give charging category for the rental: ");
                    scanf("%c", &rentals[counter]->chargingCategory);
    
    
                    counter++;
                case 2:
                    printf("\nGive license plate for finding rentals to delete ('*' for any plate): ");
                    scanf("%c", &del_number);//synarthsh
    
    
                    printf("\nGive client name for finding rentals to delete ('*' for any client): ");
                    scanf("%c", &del_name);//synarthsh
    
    
    
    
                case 3:
                    printf("Give license plate for finding rentals to show ('*' for any plate): ");
                    scanf("%c", &show_number);
    
    
                    printf("Give client name for finding rentals to show ('*' for any client): ");
                    scanf("%c", &show_name);//synarthsh kai gia to panw kai gia ayto
                case 4:
                    break;
                default:
                    printf("Invalid choice number. Try again.");
            }
        }
        while (choice!=4);
    
    
        printf("Program terminated. Bye!");
        return 0;
    }
    
    
    void licence_plate_enter(Rental** rental, int counter)
    {
        int local_count;
        for (local_count=0; local_count<=2; local_count++)
        {
            scanf("%c", rental[counter]->carLicensePlate[local_count]);
            do
            {
                if (isalpha(rental[counter]->carLicensePlate[local_count])==0)
                {
                    printf("\nError. You must first enter 3 letters\n");
                    printf("Enter the last letter again.\n");
                }
            }
            while (isalpha(rental[counter]->carLicensePlate[local_count])==0);
        }
        for (local_count=3; local_count<=6; local_count++)
        {
            scanf("%c", rental[counter]->carLicensePlate[local_count]);
            do
            {
                if (isdigit(rental[counter]->carLicensePlate[local_count])==0)
                {
                    printf("\nError. Now youu must enter 3 letters\n");
                    printf("Enter the last letter again.\n");
                }
            }
            while (isdigit(rental[counter]->carLicensePlate[local_count])==0);
        }
    local_count=0;
        while (isalpha(rental[counter]->carLicensePlate[local_count]))
        {
            putchar((toupper(rental[counter]->carLicensePlate[local_count])));
            local_count++;
        }
    }
    dont pay attention to other cases rather than case 1 and the function...

    build gives me 2 warnings and i can't understand why...tried to run the program but naturally it crashes :

    pointers in array and other questions-screenshot_15-png


    edit: dont pay attention to the comments
    Last edited by George Ioannou; 12-14-2015 at 12:53 AM.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The warnings are telling you to check the arguments to scanf: the type of the argument must match the corresponding format.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Some questions with pointers
    By kirchhoff in forum C Programming
    Replies: 5
    Last Post: 11-26-2012, 09:07 PM
  2. A few questions on pointers
    By dgs012 in forum C Programming
    Replies: 1
    Last Post: 12-01-2010, 09:53 AM
  3. Replies: 4
    Last Post: 07-01-2009, 01:53 PM
  4. questions about pointers
    By radxxx in forum C Programming
    Replies: 3
    Last Post: 04-21-2009, 11:38 AM
  5. Some questions about pointers
    By indigo0086 in forum C++ Programming
    Replies: 5
    Last Post: 09-08-2002, 02:25 PM