Hamumu Forum

Hamumu Forum (http://hamumu.com/forum/index.php)
-   Total Mayhem (http://hamumu.com/forum/forumdisplay.php?f=37)
-   -   Problem: Functions In C (http://hamumu.com/forum/showthread.php?t=24666)

REACTOR 08-26-2014 01:09 AM

Problem: Functions In C
 
I am regaining confidence and so far, know the ins and outs of a simple program, my next assignment is to write a function, and so I did by my father's words, but I don't have a clue what to do, the compiler keeps on throwing at me, unknown reference errors.
Here is my code for the main function at hand: The compiler throws no errors about it when I compile.

fmin.c
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers, the size of an array can only be from 1-100.
 * Output: The smallest number found from the array.
 * Description: This functions assigns a given array of values to a specific table, it then  *goes through a loop which
 * determines which value out of all the other values, is the smallest.
 *
 */

int fminimum ( int table[] )
{

    int min = 0;
    int tableindex = 0;
   
    min = table[tableindex];
   
    for ( tableindex = 1; table[tableindex] != -1; tableindex++ )
    {
        if ( table[tableindex] < min )
        min = table[tableindex];
    };
   
    return (min);

}

And here is my header file code:

fmin.h
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers, the size of an array can only be from 1-100.
 * Output: The smallest number found from the array.
 * Description: This functions assigns a given array of values to a specific variable, table, it then goes through a loop which
 * determines which value out of all the other values, is the smallest.
 *
 */

int fminimum ( int table[] );

When I declare my header file at the top of the program I am adding my new function to, I use "" not <>, so it's not the case with that, but whenever I say build, it gives a compilation failure error message, UNKNOWN REFERENCE TO FMINIMUM.

I don't know what I am doing wrong. I checked it up on the internet, but none of those guys give a clear explanation of what is happening.

Edit: And also, if I try to compile fmin.c, it will give an error of the same kind but telling me there is an undefined reference to main.

Hammered 08-26-2014 05:55 AM

Re: Problem: Functions In C
 
Is there a reason why this is in total mayhem?

SpaceManiac 08-26-2014 08:58 AM

Re: Problem: Functions In C
 
Quote:

Originally Posted by Hammered (Post 346545)
Is there a reason why this is in total mayhem?

Confusion about where it was supposed to go, most likely. I imagine Making Dumb Games is good though.

Actual question answer: you're experiencing the fun of trying to compile multiple C source files into one program for the first time! (It's not that bad really).

I imagine you're trying a sequence of commands something like this, perhaps with more options:
Code:

gcc main.c
gcc fmin.c

What this tells the compiler to do is to try and make a complete program using only "main.c" and another one using only "fmin.c". Unfortunately, each file contains only part of the complete program - one is missing the definition (the code body) of "fminimum", and the other is missing the "main" function.

To compile both .c files at once into a single program, you want a command sort of like...
Code:

gcc main.c fmin.c
This tells the compiler to compile both source files as a single program, which is what you want. Now the finished program contains both a "main" function and the definition of the "fminimum" function.

There are more advanced techniques for compiling projects with many many source files rather than just a few but this should get you started.

REACTOR 08-26-2014 04:27 PM

Re: Problem: Functions In C
 
Thanks Spacemaniac. I will let you know how it went.

seamonkey 08-27-2014 12:43 AM

Re: Problem: Functions In C
 
Quote:

Originally Posted by Hammered (Post 346545)
Is there a reason why this is in total mayhem?

C is utter chaos. Everybody knows that.

REACTOR 08-27-2014 02:22 AM

Re: Problem: Functions In C
 
I don't know how C is total chaos, I put this thread in Total Mayhem because I was not sure where to put it.

seamonkey 08-27-2014 04:50 PM

Re: Problem: Functions In C
 
It's not - although I'm not a huge fan. It was meant to be a joke. I s'pose a d: would have helped.

REACTOR 09-13-2014 12:58 AM

Re: Problem: Functions In C
 
Quote:

Originally Posted by SpaceManiac (Post 346546)
Confusion about where it was supposed to go, most likely. I imagine Making Dumb Games is good though.

Actual question answer: you're experiencing the fun of trying to compile multiple C source files into one program for the first time! (It's not that bad really).

I imagine you're trying a sequence of commands something like this, perhaps with more options:
Code:

gcc main.c
gcc fmin.c

What this tells the compiler to do is to try and make a complete program using only "main.c" and another one using only "fmin.c". Unfortunately, each file contains only part of the complete program - one is missing the definition (the code body) of "fminimum", and the other is missing the "main" function.

To compile both .c files at once into a single program, you want a command sort of like...
Code:

gcc main.c fmin.c
This tells the compiler to compile both source files as a single program, which is what you want. Now the finished program contains both a "main" function and the definition of the "fminimum" function.

There are more advanced techniques for compiling projects with many many source files rather than just a few but this should get you started.

Your advice worked very well, and gave me more of a clue as to what I should do next.
I compiled all my three functions along with my main one, and also successfully built all four files together. No problems so far.

But for some mysterious reason, when I run my program and get to the part where it does the fminimum operation, it just shows 0 even though the smallest number I typed in the array was 4. I tried it several times and so far, the same problem cropped up, 0, 0, 0...

I was hoping someone could point me the way to my bug, because I am really stumped at what I am doing wrong... Here are the files:

shw_ufo.c
Code:

/*
 * This program records the number of UFO sightings per day of a month.
 *
 * Date: 7th August 2014
 * Author: Sebastian
 *
 */
 
#include <stdio.h>
#include "fmax.h"
#include "fmin.h"
#include "fsum.h"

int main()

{
   
    const int MAX = 102;
   
    int ufo_table[MAX];
    int days_in_m = 0;
    int day_of_m = 1;
    int ufo_per_day = 0;
   
    int max = 0;
    int min = 0;
    int sum = 0;
   
    printf("\n");
   
    do
    {
       
    printf("UFO sighting recording.\n");
    printf("Please enter the number of days in your selected month.\n");
    printf("Valid number of days are from 1 to 100!\n==> ");
    scanf("%d", &days_in_m);
   
    /*Validating number!*/
   
        if ( days_in_m < 1 || days_in_m > 100)
        {
           
            printf("\n*** \nNot a valid number, try again\n ***\n");
        };
       
   
    } while ( days_in_m < 1 || days_in_m > 100);
   
    /*Now we get the numbers of UFOs.*/
   
    do
    {
       
        printf("\n");
        printf("Enter number of UFO sightings for day %d.\n", day_of_m);
        printf("Valid numbers are from 0 to 999.\n==> ");
        scanf("%d", &ufo_per_day);
       
        /*Validating number!*/
       
        if ( ufo_per_day > -1 && ufo_per_day < 1000 )
        {
           
            ufo_table[day_of_m] = ufo_per_day;
            day_of_m++;
           
        }
       
        else
        {
           
            printf("\n*** \nNot a valid number, try again\n ***\n");
           
        };
   
    } while ( day_of_m <= days_in_m );
   
    /*Assigning a specific value to the last index of the table to denote the end.*/
   
    day_of_m = day_of_m + 1;
    ufo_table[day_of_m] = -1;
   
    /*The last stage of the program, printing out all the values in the table!*/
   
    printf("\nNow printing out the number of UFO sightings per day which you have entered!\n\n");
   
    for ( day_of_m = 1; day_of_m <= days_in_m; day_of_m++ )
    {
       
        printf("Day[%3d] => %3d Sighting[s].\n\n", day_of_m, ufo_table[day_of_m]);
       
    };   
   
    printf("Extra statistics:\n");
   
    /*Finding the minimum number of UFO sightings entered.*/
   
    min = fminimum ( ufo_table );
   
    /*
    min = ufo_table[1];
   
    for ( day_of_m = 1; day_of_m <= days_in_m; day_of_m++ )
    {
        if (ufo_table[day_of_m] < min )
        min = ufo_table[day_of_m];
    };
    */
   
    printf("\n");
    printf("Minimum number of UFO sightings is [%3d].", min);
   
    /*Finding the maximum number of UFO sightings entered.*/
   
    max = fmaximum ( ufo_table );
   
    /*for ( day_of_m = 1; day_of_m <= days_in_m; day_of_m++ )
    {
        if ( ufo_table[day_of_m] > max )
        max = ufo_table[day_of_m];
    };
    */
   
    printf("\n");
    printf("Maximum number of UFO sightings is [%3d].", max);
   
    /*Adding the total sum of all UFO sightings.*/
   
    sum = findsum ( ufo_table );
   
    /*
    for ( day_of_m = 1; day_of_m <= days_in_m; day_of_m++ )
    {
        sum = sum + ufo_table[day_of_m];
    };
    */
   
    printf("\n");
    printf("Total sum of all UFO sightings is [%3d].", sum);
       
    printf("\n\n End of program! \n");
   
return 0;

};

fmin.c
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers.
 * Output: The smallest number found from the array.
 * Description: This functions assigns a given array of values to a specific table, it then goes through a loop which
 * determines which value out of all the other values, is the smallest, and returns it.
 *
 */

#include "fmin.h"

int fminimum ( int table[] )
{

    int min = 0;
    int tableindex = 0;
   
    min = table[1];
   
    for ( tableindex = 1; table[tableindex] != -1; tableindex++ )
    {
       
        if ( table[tableindex] < min )
        {   
           
            min = table[tableindex];
           
        };
           
    };
   
    return (min);

};

fmin.h
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers.
 * Output: The smallest number found from the array.
 * Description: This functions assigns a given array of values to a specific table, it then goes through a loop which
 * determines which value out of all the other values, is the smallest, and returns it.
 *
 */

int fminimum ( int table[] );

fmax.c
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers.
 * Output: The largest number found from the array.
 * Description: This functions assigns a given array of values to a specific table, it then goes through a loop which
 * determines which value out of all the other values, is the largest, and returns it.
 *
 */

#include "fmax.h"

int fmaximum ( int table[] )
{
   
    int max = 0;
    int tableindex = 0;
   
    for ( tableindex = 1; table[tableindex] != -1; tableindex++ )
    {
       
        if ( table[tableindex] > max )
        {
           
            max = table[tableindex];
           
        };
           
    };
   
    return (max);
   
};

fmax.h
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers.
 * Output: The largest number found from the array.
 * Description: This functions assigns a given array of values to a specific table, it then goes through a loop which
 * determines which value out of all the other values, is the largest, and returns it.
 *
 */

int fmaximum ( int table[] );

fsum.c
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers.
 * Output: The sum of all the values in the array.
 * Description: This functions assigns a given array of values to a specific table, it then goes through a loop which
 * adds all the given values in the array up, and returns it.
 *
 */

#include "fsum.h"

int findsum ( int table[] )
{

    int sum = 0;
    int tableindex = 0;

    for ( tableindex = 1; table[tableindex] != -1; tableindex++ )
    {
       
        sum = sum + table[tableindex];
       
    };
   
    return (sum);
   
};

fsum.h
Code:

/*
 * Author: Sebastian
 * Date: 26/AUG/2014
 *
 * Input: An array of integers.
 * Output: The sum of all the values in the array.
 * Description: This functions assigns a given array of values to a specific table, it then goes through a loop which
 * adds all the given values in the array up, and returns it.
 *
 */

int findsum ( int table[] );

The two other custom functions, fmaximum, findsum, seem to work, but the fminimum function seems to have a problem which I don't know how to fix.

seamonkey 09-13-2014 02:21 AM

Re: Problem: Functions In C
 
I don't know what your bug is (it's 2am and I'm tired), I'm just here to say you not utilizing index 0 bugs me to no end.
Also, a while loop makes a lot more sense for what you are doing - unknown number of iterations and all.

hyperme 09-13-2014 09:03 AM

Re: Problem: Functions In C
 
Firstly: C, like most languages, uses zero indexing. I have no idea how memory works in C, but in C++ or Java starting from 1 is a really neat way to waste memory.


Secondly: Your for loops are completely wrong. Unless C treats all attempts to access invalid array indexes as -1, they aren't going to work*. At all. Instead, find out the length of your array, put in a variable then have something like this:

Code:

for(int i = 0; i <= arrayLength; i++)
{
//Do stuff
}

I'm fairly certain this will fix your problem.

*Assuming arrays work in C and C++ the same, they won't work because arrays are bunch of data store concurrently in memory. Data is accesses based on the array type by using an offset from the memory address of element 0 of the array. This means C doesn't care that you're out of the arrays bounds. Your loop will continue until it hits a location storing a -1. Any other data in between will be process by the function as an int. Since you're roaming all over the memory map, it's likely that you'll hit an empty memory location, which is read as 0. (In Java, your program would exception. For several reasons.)

seamonkey 09-13-2014 10:22 AM

Re: Problem: Functions In C
 
@hyperme: he does have an EOF (Ok it isn't a file, but still), marker in his array - so he shouldn't be going out of bounds. He is (in theory) guaranteed to hit a -1 at the end of the user inputted data - which is why

That said your method of initializing your array is also a waste of memory - why reserve 102 slots if you don't need them? Instead initialize the array to have MAX elements, where you define MAX to be the user inputted number. (currently you set the user input to days_in_m)


I said last night that a while loop would be a better loop. This is because in general the condition to run the loop should be related to the updater and the initial variable, which yours is not. For example

Code:

while(table[tableindex] != -1)
{
//Do stuff

tableindex++;
}

One possible bug is that Hyperme is correct, and your loop is escaping your -1. I don't see exactly how this happens, but I do know a way to test it. When you initialize an int[] it fills it by default with 0's. If you have an array that is partially filled and it escapes past your -1 marker, it will default back to a zero. An easy way to test whether this is the case is to fill the array with a bunch of 999's at the start, and then run the program again and look at the max result.

REACTOR 09-15-2014 02:58 AM

Re: Problem: Functions In C
 
Well you guys were certainly right about there being an index skip,

day_of_m = day_of_m + 1;

This line was my problem, I forgot that when the previous loop was doing it's thing, finishing at the end, it moved the index up by one, and then with this function, it also lead the index up by one too.

Well anyway guys, thanks for your help.

REACTOR 10-02-2014 03:56 AM

Re: Problem: Functions In C
 
I have been progressing through C, but I hit another block again, it apparently looks like the program is going out of boundries when it reaches the end of the enterintit function, but I am stumped again as to what the problem may be.

https://www.dropbox.com/s/d1ubvwwkx2...shw_ufo.c?dl=0 ; shw_ufo.c
https://www.dropbox.com/s/hju6pt77tk...s_ei_it.c?dl=0 ; table occupier
https://www.dropbox.com/s/ugwatsls1a...s_ei_it.h?dl=0
https://www.dropbox.com/s/m87qxzhphn...rinteft.c?dl=0 ; printout
https://www.dropbox.com/s/asskrlkn29...rinteft.h?dl=0
https://www.dropbox.com/s/8jiasam0cbrd7x6/fsum.c?dl=0 ; fsum
https://www.dropbox.com/s/pekpx92o72hs9x8/fsum.h?dl=0
https://www.dropbox.com/s/zx5qr9f9lkowlrf/fmin.c?dl=0 ; fmin
https://www.dropbox.com/s/vwcs2cws3vdvwkf/fmin.h?dl=0
https://www.dropbox.com/s/nm9f10fvcmhwmaq/fmax.c?dl=0 ; fmax
https://www.dropbox.com/s/40mdi512rt7fdim/fmax.h?dl=0
https://www.dropbox.com/s/yltk9c71qxyxygd/dsort.c?dl=0 ; dsort
https://www.dropbox.com/s/yltk9c71qxyxygd/dsort.c?dl=0
https://www.dropbox.com/s/i9n1hz04ehiuyj2/fswap.c?dl=0 ; fswap
https://www.dropbox.com/s/0xx6no3te6x3ul4/fswap.h?dl=0
https://www.dropbox.com/s/xz1sy2p9eh...nterint.c?dl=0 ; enterint
https://www.dropbox.com/s/4a04omzxxy...nterint.h?dl=0

seamonkey 10-02-2014 09:32 AM

Re: Problem: Functions In C
 
Some things:
s_ei_it.c doesn't return anything. Your description at the top says it does. (hence it being void)

In the same file you run into some problems at your if statement. The first problem is that you validate the number ilimit, and it is excluded in your if statement, meaning it wouldn't get stored, and the program would ask the user for the same day again. I don't think you want a special case for when ilimit is entered.

The other problem with this if statement is that (assuming you don't want the program to just ask the user for another number on the same day when ilimit is entered), the if statement is totally unnecessary. The if statement's condition is otherwise ensured as true because the if's condition is the exact opposite of the while loop's condition.

Lastly the idx/idx2 variable stuff is confusing and annoying. It would be really good if you literally just put idx + 1 in your printf statement and the final statement and just eliminate idx2. (and put idx in the larger while loop condition and remove the = of course)

REACTOR 10-03-2014 12:58 AM

Re: Problem: Functions In C
 
Quote:

Originally Posted by seamonkey (Post 346956)
Some things:
s_ei_it.c doesn't return anything. Your description at the top says it does. (hence it being void)

In the same file you run into some problems at your if statement. The first problem is that you validate the number ilimit, and it is excluded in your if statement, meaning it wouldn't get stored, and the program would ask the user for the same day again. I don't think you want a special case for when ilimit is entered.

The other problem with this if statement is that (assuming you don't want the program to just ask the user for another number on the same day when ilimit is entered), the if statement is totally unnecessary. The if statement's condition is otherwise ensured as true because the if loop's condition is the exact opposite of the while loop's condition.

Lastly the idx/idx2 variable stuff is confusing and annoying. It would be really good if you literally just put idx + 1 in your printf statement and the final statement and just eliminate idx2. (and put idx in the larger while loop condition and remove the = of course)

Well thanks for your reply! I managed to fix my function, and also any other problems that cropped up along the way. YAY!! XD

Though, I do intend to keep idx2, if the final result is bug free, than what's the diff?

hyperme 10-03-2014 01:45 AM

Re: Problem: Functions In C
 
Quote:

Originally Posted by REACTOR (Post 346963)
Though, I do intend to keep idx2, if the final result is bug free, than what's the diff?

It makes the program harder to read, and it wastes memory.

(Although memory generally isn't an issue on modern computers.)

seamonkey 10-03-2014 02:21 PM

Re: Problem: Functions In C
 
One problem programmers run into is when they work on someone else's code, or someone works on your code, or even working on your own code years after you start it, you have NO idea what approach you used. This is why we try to use as few variables as possible, and give them descriptive names. (I have no idea what idx and idx2 stand for btw) It causes less headaches further on down the line.


now that's all said I admit I am terrible about doing this when I am coding. var1 var2 var3 have become names of things in some of my stuff. And commenting on my code...don't get me started.

REACTOR 10-03-2014 08:46 PM

Re: Problem: Functions In C
 
idx stands for index, since index is a reserved word, I had to think of something else.

REACTOR 11-09-2014 08:51 PM

Re: Problem: Functions In C
 
Everything is currently going great for me in C, had no major problems which couldn't be fixed.

But I had been recently assigned to write a function which counts characters in a string, so far it worked perfectly, but I have to think of how it can be used....

Any ideas?

calthax 11-10-2014 02:55 AM

Re: Problem: Functions In C
 
It could be used to sort strings by the amount of characters


All times are GMT -7. The time now is 03:36 AM.

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2017, vBulletin Solutions Inc.