简体   繁体   中英

Storing values in an array in a for loop

Edit: For this assignment I need to input how many rectangular "zones" we are putting in on a Cartesian grid. Our 4 inputs are 2 (x,y) coordinates x1 , y1 , x2 , y2 , for each zone. The coordinates should be the bottom left corner and the top right corner of the rectangle. we are checking to see if each zones overlaps with any of the previous zones, so I need the coordinates of the previous zones to be saved so that I can use them later for checking for overlaps. My professor is requiring us to use dynamic memory allocation for this program.

I'm trying to create an array of x and y coordinates to compare with each other. Each iteration of the for loop is going to ask for 2 coordinate points ( x1 , y1 , x2 , y2 ) to compare with the next set of points, so each time the for loop ends, those coordinates entered need to be saved. I've already used malloc() for each of the values, I just need help figuring out how to save them from being erased when the next for loop starts in an efficient way. Should I create an array for each of the values or would that be inefficient?

int i, j;
int zones, *x1, *y1, *x2, *y2;

scanf("%d", &zones);

x1 = malloc(sizeof(int)*zones);
y1 = malloc(sizeof(int)*zones);
x2 = malloc(sizeof(int)*zones);
y2 = malloc(sizeof(int)*zones);

for(i=0; i<zones; i++)
{
    scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
}

After I scan my values I'm not sure where to go from there. Also I'm not sure if I'm entering in malloc correctly. I want each value to be big enough to hold values equal the number of zones that will be asked.

You have created a set of buffers for storing ints of size zones. You have 4 variables which point to the first byte in each buffer (x1, y1, x2, y2).

You have a small error in your scan statement, scan expects pointers to the memory where you want to store your value. But x1 etc are already pointers, so you don't need &x1, just x1 will do what you need.

Next you want to advance the pointers to scan into the next memory location in the buffer you created for your array. You can just increment the pointers after each scan; eg x1++ . This will put each value in the subsequent location in your buffer.

But this will also loose the reference to the buffers themselves. You can move the pointers back to the beginning of the buffers after the loop (eg - x1 = x1 - zones) or you can just create a different pointer to iterate over the buffer which might be more readable.

Your read statement should be

scanf("%d%d%d%d", &x1[i], &y1[i], &x2[i], &y2[i]);

But you should also handle the case where the input is incorrect; ie, when the user mistypes and enters something that is not an integer value.

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