Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

c - dynamic memory allocation and dynamic array

I need to write a program, that will ask a user to enter a number of how many ints they would like to enter.. so the output would look like

Enter number of Ints (must be greater then 1)

and they would input a number between 2 - infinity (if they really wanted to go that far)

at that point i would scanf that number and set it to a variable

now with that number, i want to run a for loop to ask them to begin entering their Ints

for (count = 0; count < numofInts; count++)
{
    printf("    Enter an integer: ");
   scanf("%d", &Number);
}

the problem im having is that i need to make sure that it records every number that they enter, so i need to have those values stored to an array, but the number of elements of the array must be dynamic so that it can change depending on the numofInts, I'm supposed to use Malloc() to create a dynamic memory allocated space, and i understand that it creates a variable with a memory space of what ever i set the malloc to, but i don't know how to store a series a variables to that space, and then call them back as i need them.

The end result of the program is supposed to take a number like 123456789, and cycle through the number storing the intergers as the "largest" int, and then spit out which int is the largest, so like x = 1234567890, x % 10, x = 0, largest = x, x / 10, x % 10, x = 9, if x > largest, largest = x, and just loop that till it cycles through the whole number, and store that number at the very end. I have that part down, but because i have to take a series of numbers and run this loop for all of those numbers, i need to be able to store and recall those values and place them in the loop to be able to store the largest digits of those numbers

any help with this problem would be greatly appreciated, i just have not been able to figure out how to use malloc or to create a dynamic array and most of the tutorials ive read online or watched from youtube are about C++ and i need to do this with just C...

http://pastebin.com/PZyvEQ4J

what i have so far

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After you read numInts, you allocate the array like so:

int* arr = malloc(numInts*sizeof(int));

Now you populate the array with your already existing function and assigning the values read to the array.

I'm not going to give you a full solution, since this is homework and wouldn't help you, but you access the i'th element of the array with the [] operator:

arr[i];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...