Thread: Searching through an Array using Pointers

  1. #1
    Registered User towely's Avatar
    Join Date
    Oct 2009
    Posts
    12

    Exclamation Searching through an Array using Pointers

    I'm continuing on the code discussed in this thread:
    Confused parsing a CSV txt file... strtok, fgets, sscanf

    I have fourteen arrays populated with values, each of the arrays representing a different variable. The arrays are populated by using sscanf to move the values in a CSV file into the arrays. The first five arrays represent the values of JulianDay (which I won't be incorporating), Month, Day, Hour, Minute.

    Now that I have the arrays populated, I'd like to search through them based on user-defined values. This will allow me to search through the CSV files to find the correct line (containing the correct month, day, hour, and minute) so I can gather the information stored on that line for that particular date and time.

    For example: a user inputs a month, day, hour, and minute. The program then will compare the user-defined Month with the first element in the Month array. If the values do not match, the program moves onto the next element of the Month array and checks for a match. When a match occurs, the value of that element of the array is stored into a variable, (which is the equivalent line number in the CSV file -1) and then the program begins checking if the user-defined day is stored in that element, and if not, it moves onto the next one, etc.

    This process continues until the correct element number representing the proper month, day, hour, and minute has been chosen. At this point, I'd like to store the values stored at that element number within all the arrays into variables, so I can print them. This will give me an output of the correct information for the proper date and time.

    Now that I've explained what the code should do, I would appreciate some help with what I'm doing wrong here. I'm not sure where I am going wrong, but the pointers are pointing to incorrect values within the CSV file when I check the output. I think I'm calculating the value of i2 incorrectly. Here's the code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
    int ValidDateTime;
    int Year;
    int Month;
    int Day;
    int Hour;
    int Minute;
    int Feb;
    
    char line[300];
    int i = 0;
    int aJulianDay[300];
    int aDay[300];
    int aMonth[300];
    int aHour[300];
    int aMinute[300];
    float a1[300];
    float a2[300];
    int a3[300];
    int a4[300];
    int a5[300];
    int a6[300];
    int a7[300];
    int a8[300];
    int aHazardRating[300];
    const int Multiple = 5;
    int FiveMin;
    
    //------------------------------------------------------------------
    // This loop takes the input from the user, then checks if it's a valid date.
    // If it's not, it prompts the user to enter a valid date and loops back.
    // If it's a valid date, the loop ends and program continues
    
    do
    	{
    	printf("Please Enter a Date and Time\n(Numerical Format):\n");
    	printf("Year: ");
    	scanf("%d", &Year);
    	printf("Month: ");
    	scanf("%d", &Month);
    	printf("Day: ");
    	scanf("%d", &Day);
    	printf("Hour: ");
    	scanf("%d", &Hour);
    	printf("Minute: ");
    	scanf("%d", &Minute);
    
    
    	//Check if leap year
    	//If so, Feb has 29 days. If not, Feb has 28 days
    
    	if(Year % 4 == 0 && Year%100 != 0 || Year % 400 == 0)
    		{
    		Feb = 29;
    		}
    	else
    		{
    		Feb = 28;
    		}
    
    		//Check if it's a valid date & time
    		//If so, the loop ends. If not, loop continues
    
    	if(Month = 1 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 2 && Day > Feb)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 3 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 4 && Day > 30)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 5 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 6 && Day > 30)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 7 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 8 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 9 && Day > 30)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 10 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 11 && Day > 30)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Month = 12 && Day > 31)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Hour > 23 || Hour < 0)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    
    	if(Minute > 59 || Minute < 0)
    		{
    		printf("Please Enter a Valid Date And Time");
    		ValidDateTime = 0;
    		}
    	else
    		{
    		ValidDateTime = 1;
    		}
    	} 
    //Loop ends if it's a real date and time	
    while(ValidDateTime = 0);
    
    //----------------------------------------------------------------------
    //If the minute chosen was not a multiple of 5, this code rounds it to the nearest 5 minutes
    
    FiveMin = Minute - (Minute % Multiple);
    
    if (Minute % Multiple != 0)
    	{
    	if ( (Minute % Multiple) > ((int)Multiple/2) )
    		{
    		FiveMin += Multiple;
    		}
    
    	printf ("Your selected minute is unavailable, the time has been rounded to the nearest multiple of 5 minutes.\n");
    
    	}
    //-----------------------------------------------------------------------
    
    // This code opens the CSV file
    
    //RT mode means Read-only Text file
    FILE *pFile;
    pFile = fopen("c:\\abc.txt", "rt");
    
    
    
    //-------------------------------------------------------------------------
    
    // Load each different 'column' of values into an array
    
    
    //fgets gets a string from a file
    //one string per line
    
    while(fgets(line, sizeof line, pFile) != NULL)
    {
    	// sscanf reads the data from the strings and stores it in arrays
    	// since the line is in a string, it finds each of the values and stores
    	// them into the specified arrays. The loop does this for each line
    	// so, each julian day will be read into array a[] each time there's a line
    	// Thus each variable is stored into a different array 
    	if(sscanf(line, "%d,%d,%d,%d,%d,%f,%f,%d,%d,%d,%d,%d,%d,%d", &aJulianDay[i], &aDay[i], &aMonth[i], &aHour[i], &aMinute[i], &a1[i], &a2[i], &a3[i], &a4[i], &a5[i], &a6[i], &a7[i], &a8[i], &aHazardRating[i]) == 14)
    		{
    		++i;
    		}
    }
    
    //Close the file
    fclose(pFile);
    
    printf("%d\n",aDay[5]);
    printf("%d\n",aMonth[5]);
    printf("%d\n",aHour[5]);
    printf("%d\n",aMinute[5]);
    printf("%f\n",a1[5]);
    printf("%f\n",a2[5]);
    printf("%d\n",a3[5]);
    printf("%d\n",a4[5]);
    printf("%d\n",a5[5]);
    printf("%d\n",a6[5]);
    printf("%d\n",a7[5]);
    printf("%d\n",a8[5]);
    printf("%d\n",aHazardRating[5]);
    
    getch();
    
    
    //-------------------------------------------------------------------------
    
    //This code SEARCHES through the arrays for the user-selected values
    
    
    //Point a pointer at the first element of the Day array
    
    int *ptr;
    
    ptr=&aDay[0];
    
    
    //Point a pointer at the first element of the Month array
    int *ptr2;;
    ptr2=&aMonth[0];
    
    
    //Point a pointer at the first element of Hour array
    int *ptr3;
    ptr3=&aHour[0];
    
    
    //Point a pointer at the first element of Minute array
    int *ptr4;
    ptr4=&aMinute[0];
    
    //Make a counter to store which element of the array you are in
    int i2 = 0;
    
    
    //Search through the array for the user-selected Day value
    while (*ptr != Day)
    	{
    	i2++;
    	ptr++;
    	}
    
    //Go into the Month array at the same array element number as the Day loop stopped in
    ptr2=&aMonth[i2];
    
    //Search through it until the user-selected month value is found
    while (*ptr2 != Month)
    	{
    	i2++;
    	ptr2++;
    	}
    
    //Go into the Hour array at the same array element number as the Month loop stopped in
    ptr3=&aHour[i2];
    
    //Search through it until the user-selected month value is found
    while (*ptr3 != Hour)
    	{
    	i2++;
    	ptr3++;
    	}
    
    //Go into the Minute array at the same array element number as the Hour loop stopped in
    ptr4=&aMinute[i2];
    
    //Search through it until the user-selected month value is found
    while (*ptr4 != FiveMin)
    	{
    	i2++;
    	ptr4++;
    	}
    
    //At this point, you are in the correct row (array location), marked by i2
    
    //Load all values within the proper array location into variables
    //From all 14 of the arrays
    
    //Year, Month, Day, Hour, FiveMin all already correctly set
    float SolarZe = 0;
    float SolarAz = 0;
    int NumPixels1 = 0;
    int NumPixels2 = 0;
    int NumPixels3 = 0;
    int NumPixels4 = 0;
    int NumPixels5 = 0;
    int HazForumulaOutput = 0;
    int HazardRating = 0;
    
    SolarZe = a1[i2];
    SolarAz = a2[i2];
    NumPixels1 = a3[i2];
    NumPixels2 = a4[i2];
    NumPixels3 = a5[i2];
    NumPixels4 = a6[i2];
    NumPixels5 = a7[i2];
    HazForumulaOutput = a8[i2];
    HazardRating = aHazardRating[i2];
    
    printf("location: %d\n", i2);
    printf("Year: %d\n", Year);
    printf("Month: %d\n", Month);
    printf("Day: %d\n", Day);
    printf("Hour: %d\n", Hour);
    printf("Minute: %d\n", FiveMin);
    printf("Solar Zenith: %f\n", SolarZe);
    printf("Solar Azimuth: %f\n", SolarAz);
    printf("Number of Pixels in Hazard Rating 1: %d\n", NumPixels1);
    printf("Number of Pixels in Hazard Rating 2: %d\n", NumPixels2);
    printf("Number of Pixels in Hazard Rating 3: %d\n", NumPixels3);
    printf("Number of Pixels in Hazard Rating 4: %d\n", NumPixels4);
    printf("Number of Pixels in Hazard Rating 5: %d\n", NumPixels5);
    printf("Hazard Formula Output: %d\n", HazForumulaOutput);
    printf("Maximum Hazard Rating: %d\n", HazardRating);
    
    
    getch();
    return 0;
    
    }
    Here's an example of the format of the CSV file:
    The format goes: JulianDay(not being used),Day,Month,Hour,Minute, then some other values.

    Code:
    299, 26, 10, 8, 0, 85.539068, 114.966376, 49899, 5755, 3751, 3014, 994, 89688, 5
    299, 26, 10, 8, 15, 83.402953, 117.925606, 47183, 7941, 4041, 3164, 1084, 93264, 5
    299, 26, 10, 8, 30, 81.309957, 120.940738, 47109, 7273, 5212, 2600, 1219, 93786, 5
    299, 26, 10, 8, 45, 79.275465, 124.019094, 48113, 5758, 6119, 2256, 1167, 92845, 5
    299, 26, 10, 9, 0, 77.310476, 127.167473, 48561, 5522, 5866, 2362, 1102, 92161, 5
    299, 26, 10, 9, 15, 75.424519, 130.392021, 49054, 5333, 5635, 2426, 965, 91154, 5
    299, 26, 10, 9, 30, 73.626649, 133.698080, 49708, 5028, 5305, 2497, 875, 90042, 5
    299, 26, 10, 9, 45, 71.925819, 137.089994, 50506, 5833, 3787, 1982, 1305, 87986, 5
    299, 26, 10, 10, 0, 70.331002, 140.570898, 51082, 6267, 2608, 2221, 1235, 86499, 5
    299, 26, 10, 10, 15, 68.851203, 144.142484, 51679, 5357, 3216, 1781, 1380, 86065, 5
    299, 26, 10, 10, 30, 67.495392, 147.804762, 52272, 4838, 3220, 1716, 1367, 85307, 5
    299, 26, 10, 10, 45, 66.272386, 151.555836, 54583, 2756, 2751, 2259, 1064, 82704, 4
    Any help with where I'm going wrong would be appreciated.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Before you get too far into this...

    1) Consider reorganizing your data as an array of structs... each struct containing all the data from one line of the file. If you are unsure how many lines in a given file, use linked lists instead of arrays... Believe me it will be much easier than what you're doing now.

    2) Look at the C time functions... you can represent any second from 1970 to 2140 (iirc) as a single DWORD value and the various functions will let you search on a single test... if (structTime = userTime)...

    If you do these two things you will probably cut your code size in half and have a program that runs with far fewer problems or hesitations.
    Last edited by CommonTater; 07-07-2011 at 06:44 PM.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by CommonTater View Post
    to 2140 (iirc)
    2038 - Year 2038 problem - Wikipedia, the free encyclopedia


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by CommonTater View Post
    Before you get too far into this...

    1) Consider reorganizing your data as an array of structs... each struct containing all the data from one line of the file. If you are unsure how many lines in a given file, use linked lists instead of arrays... Believe me it will be much easier than what you're doing now.
    You really need to do Tater option 1; it will be many times easier to solve this problem.

    Cprogramming.com FAQ > All about structures

    Tim S.
    Last edited by stahta01; 07-07-2011 at 07:18 PM.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by quzah View Post
    Oh, ok... I wasn't sure about that. Or was it 2140 for int64 time?

    Thanks.

    The good news is neither really affects our OP...

  6. #6
    Registered User towely's Avatar
    Join Date
    Oct 2009
    Posts
    12
    I read the link on structures, and I understand what they are now, but I don't understand how using those will make my task any easier. I really think I'm pretty close to having this problem solved, close enough that I don't want to have to spend another two weeks re-learning how to work with structs and populate them with CSV files, etc.

    See, the thing is, I'm a university student who got hired on as a research assistant for the summer. I'm not a Computer Science major, and was hired because I created a very basic program in Visual Basic last semester. I was tasked with doing computer programming in C this summer, which I've never touched before. I have been having a really hard time getting my mind wrapped around a lot of concepts, as many things in C are totally foreign to me. I've spent the last month teaching myself C and working on all this code, and I'm afraid that if I have to start from scratch and spend another week or two re-learning how to do what I'm doing, I'm afraid my Prof will think I'm incompetent and I'll get dropped as an RA. I really can't handle that financially, so any help with the actual code I have would be great.

    I know I'm really close to having it working, as it pulls info from a particular line in the file. It's just not the correct line.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Compare:
    Code:
    #define PEOPLE 400
    char firstname[ PEOPLE ][ 20 ], middleinitial[ PEOPLE ], lastname[ PEOPLE ][ 30 ];
    int age[ PEOPLE ], sex[ PEOPLE ];
    ...
    void sortpeoplebyage( firstname, middleinitial, lastname, age, sex );
    Compared to:
    Code:
    struct person
    {
        char firstname[ 20 ];
        char middleinitial;
        char lastname[ 30 ];
        int age;
        int sex;
    } people[ PEOPLE ];
    ...
    void sortpeoplebyage( people );
    Can you see the benefit of carrying your clothes in a suitcase, instead of just heaping them in your arms?


    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by towely
    I read the link on structures, and I understand what they are now, but I don't understand how using those will make my task any easier.
    Each line in your CSV file is some kind of record. Currently, you store the individual fields of the various records into separate arrays. If you had some kind of record structure, you could store them into a single array of records, which tends to be easier to manage. Later, it could even help you a great deal if you want to say, sort the records by some field and display them.

    That said, one of the things I notice about your code in the original post is that you should be more careful of the difference between = and ==. Another thing is that you need to format your code better: especially since after your time as an RA is up, another poor fellow (or even the researcher, who you may one day want to call upon for a resume reference) may be called upon to maintain what you wrote.
    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

  9. #9
    Registered User towely's Avatar
    Join Date
    Oct 2009
    Posts
    12
    Quote Originally Posted by quzah View Post
    Can you see the benefit of carrying your clothes in a suitcase, instead of just heaping them in your arms?


    Quzah.
    Sure, it looks nicer, but isn't the code that I have technically a valid way to do what I want to accomplish? I'm not a computer science student, and there's a good chance I will never touch C programming again in my life after September comes around. Therefore, I don't care if I am doing it an ugly way, and don't have time to learn a completely new way to use C. I just need to have the work done.

    Will you guys seriously not help me with the question at hand?
    Last edited by towely; 07-07-2011 at 08:09 PM.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by towely
    Therefore, I don't care if I am doing it an ugly way, and don't have time to learn a completely new way to use C. I just need to have the work done.
    Sometimes, to "waste" time is to save time.

    Quote Originally Posted by towely
    Will you guys seriously not help me with the question at hand?
    Read my post #8 for two pointers. Fix them and post the resulting code, after having tested.
    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

  11. #11
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by towely View Post
    .....
    I know I'm really close to having it working, as it pulls info from a particular line in the file. It's just not the correct line.
    Well, which line does it pull it from. Is it always a certain number of lines off or does it vary depending on the search?
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Code:
    //Go into the Month array at the same array element number as the Day loop stopped in
    ptr2=&aMonth[i2];
    
    //Search through it until the user-selected month value is found
    while (*ptr2 != Month)
    	{
    	i2++;
    	ptr2++;
    	}
    Why are you using pointers; if you do not know enough to use structures, it is very unlikely you know enough to use pointer arithmetic correctly or safely.

    How is your code better than this

    Code:
    //Search through it until the user-selected month value is found
    while (aMonth[i2] != Month)
    	{
    	i2++;
    	}
    Note: The order of Month day hour searches matters, doing month, day, hour is more likely to get the right answer.
    This assumes the data is sorted in chronological order.

    Note: You will get false matches using your code (or even the code in this post of mine); this will happen if the value you are searching for is not in the list.
    Note: Using structure makes search easier.

    Tim S.
    Last edited by stahta01; 07-07-2011 at 08:38 PM.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by towely View Post
    Therefore, I don't care if I am doing it an ugly way,
    I do, because I'm the one reading through a hundred lines of ugly code with variable scattered randomly throughout, and everything done in a single function, all because you are too lazy to:
    Quote Originally Posted by towely View Post
    to learn a completely new way to use C. I just need to have the work done.
    Besides, you've already been told what you are doing wrong. You just saw two paragraphs and panicked because you had to read more words than a sentence in "Dick and Jane". (Don't click that link though, because it has way more than just two paragraphs.)
    Quote Originally Posted by towely View Post
    Will you guys seriously not help me with the question at hand?
    Yes, I will seriously not help you.


    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User towely's Avatar
    Join Date
    Oct 2009
    Posts
    12
    Quote Originally Posted by stahta01 View Post
    Note: The order of Month day hour searches matters, doing month, day, hour is more likely to get the right answer.
    This assumes the data is sorted in chronological order.
    Aha!
    This was my problem, the code works perfectly now. I should have realized that I needed to search via the correct order of m/d/h/m, not via the order the arrays are in. Thanks for the tip!

    Also, thanks for the notes on the == signs, laserlight. I fixed those too.

    I'm beside myself that I didn't have to learn structures.
    Last edited by towely; 07-07-2011 at 09:08 PM.

  15. #15
    Registered User towely's Avatar
    Join Date
    Oct 2009
    Posts
    12
    Quote Originally Posted by quzah View Post
    Yes, I will seriously not help you.


    Quzah.
    Wow, that's a fantastic attitude.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 08-23-2010, 02:31 PM
  2. Help with my searching my array
    By snooki in forum C++ Programming
    Replies: 8
    Last Post: 03-25-2010, 05:18 PM
  3. Replies: 4
    Last Post: 07-01-2009, 01:53 PM
  4. Searching an array with pointers
    By pxleyes in forum C Programming
    Replies: 16
    Last Post: 03-23-2004, 05:07 PM
  5. Searching an array
    By passy in forum C Programming
    Replies: 7
    Last Post: 08-14-2003, 11:10 AM