简体   繁体   中英

Pointers & Dynamic Memory Allocation in C

I'm fairly new to the language C and am getting a bit muddled up with pointers & dynamic memory allocation. What I'm trying to do is read in command line arguments and store them in dynamic memory allocation; then printing them out. For example if I typed ./rpd 4 3 2 3 8 then argv[1] (4) should be decremented and the other 3 values (3, 2, 3, 8) should follow. The output should look like:

Person 1 has 3 cars. Person 2 has 2 cars. Person 3 has 3 cars. Person 4 has 8 cars.

My Code is:

  #include <stdio.h>

int main(int argc, char *argv[]) {
    /** argc is number of arguments at command line*/
    /** argv[] is an array of pointers to character strings
        i.e. argv 1 points to argc 1 */
    int numberOfCars;
    char *person;
    int i;
    int j;

    // Allocate the size of the array for each element of char
    person = malloc(sizeof(numberOfCars) *argc);

    for(i = 2; i < argc; i++) {
        /** Convert char to int */
        numberOfCars = atoi(argv[i]);
        person = atoi(argv[1]);
        if(person > 0){
            for(j = 2; j < person; j--) {
                printf("Person %d has %d cars \n", person--, numberOfCars);
            }
        } else {
            /** DO NOTHING */
        }
    }
    return person;
}

I'm sorry if this is a little confusing (or naive) of me; but I am extremely new to this language so I'm still trying to get my head around everything.

Thanks alot for any help :)

Try something like this:

#include <stdio.h>

int main(int argc, char *argv[]) {
    /** argc is number of arguments at command line*/
    /** argv[] is an array of pointers to character strings
        i.e. argv 1 points to argc 1 */
    int numberOfCars;
    int i;

    for(i = 1; i < argc; i++) {
        /** Convert char to int */
        numberOfCars = atoi(argv[i]);
        printf("Person %d has %d cars \n", i, numberOfCars);
    }

    return 0;
}

Then tweak it for your needs. You dont need to specify the number of people for the first input argument, since it's implied by the number of cars you specify for each person.

atoi returns an int, but person is a char pointer.

#include <stdio.h>
int main(int argc, char *argv[]) {
   /** argc is number of arguments at command line*/
   /** argv[] is an array of pointers to character strings
    i.e. argv 1 points to argc 1 */
   int numberOfCars;
   int i;
   int p = 0;
   for(i = 2; i < argc; i++) {
      /** Convert char to int */
      numberOfCars = atoi(argv[i]);
      printf("Person %d has %d cars \n", ++p, numberOfCars);
   }
   return 0;
}

Output:

$ ./a.out 4 3 2 3 8 10
 Person 1 has 3 cars 
 Person 2 has 2 cars   
 Person 3 has 3 cars 
 Person 4 has 8 cars 
 Person 5 has 10 cars

Code

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int numberOfCars;
    int *person;
    int i;

    person = malloc(sizeof(int) * argc);

    for(i = 1; i < argc; i++)
    {
        numberOfCars = atoi(argv[i]);
        if (i == 1)
            numberOfCars--;
        person[i] = numberOfCars;
        printf("Person %d has %d cars\n", i, numberOfCars);
    }

    free(person);
    return 0;
}

Sample output

$ ./rpd 4 3 2 3 8
Person 1 has 3 cars 
Person 2 has 3 cars 
Person 3 has 2 cars 
Person 4 has 3 cars 
Person 5 has 8 cars
$

Explanation

#include <stdio.h>
#include <stdlib.h>

You need <stdlib.h> to declare malloc() and free() . When you use malloc() , you should also use free() .

int main(int argc, char *argv[])
{
    int numberOfCars;
    int *person;
    int i;

The variable j is unused in the revision and therefore removed. The variable person is changed to int * as person[i] will store the number of cars person i has.

    person = malloc(sizeof(int) * argc);

I changed the sizeof() to int ; it would also be possible to use sizeof(*person) and there are good reasons for preferring that.

    for (i = 1; i < argc; i++)
    {
        numberOfCars = atoi(argv[i]);

The assignment person = atoi(argv[1]); was erroneous at multiple levels. It leaked the memory assigned by the malloc() ; it assigned an int to a pointer (originally a char * ).

        if (i == 1)
            numberOfCars--;

This deals with the 'subtract one from first argument' requirement.

        person[i] = numberOfCars;

This records the number of cars that person i has. It isn't used; it could be used in place of numberOfCars in the printf() statement.

        printf("Person %d has %d cars\n", i, numberOfCars);

Spaces at the end of a line are a bête noire of mine. Don't put blanks before a newline.

    }

    free(person);

Release the memory that was allocated. In this toy program, it isn't critical (the o/s is about to release all the resources used by the program), but if it was a function in a big program and it omitted the free() , it would leak memory each time it is called. Get into the habit of writing the free() for each malloc() as soon as you've written the malloc() . (Or, at least, make sure you know where you will write the free() , and do write the free() before compiling, let alone testing, the program.)

    return 0;
}

What do you want to store dynamically? If want to only print the values as you mentioned in question. You would not require dynamic allocation at all.

If at all you want to store them use char **person; //instead of *person and keep allocation memory per person by using

person[i] = malloc(sizeof(argv[i])+sizeof("person has cars")); //not sure of ur required format to store you can change it accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM