xavier666 56 Junior Poster

I was writing a file copying program. Mind you this is an any file copier. That is, at this moment, this function can copy only text files but i'm trying to copy mp3 files, avi files, mkv files etc, which this cannot. Here is just the copying function. However it was not working...

int copy(char * source, char * target)
{
	FILE * f_source;
	FILE * f_target;
	char ch = 0;

	f_source = fopen(source,"rb");  //  OPENING IN BINARY MODE(READ)

	if(f_source == NULL)
	{
	    return 0;                   //  FILE NOT FOUND!
	}

	f_target = fopen(target,"wb");  //  OPENING IN BINARY MODE(WRITE)

	while(ch != EOF)
	{
	    ch = getc(f_source);
	    if(ch != EOF)
            putc(ch,f_target);
	}

	fclose(f_source);
	fclose(f_target);

	return 1;
}

So in desperation, i changed the type of ch in LINE 5 to int and then the program was running fine. I want to know why?
Thanks in advance!!

xavier666 56 Junior Poster

Please, do not hijack threads. Start a separate thread instead.
As for your question, i'll be saying it in short. system("pause") creates a pause during a running program, which can be resumed by pressing any key. It("pause") is a Windows specific command and is generally not recommended

xavier666 56 Junior Poster

Hello vanan4u

These are your errors
1) You have declared the return type of main as void but returned an integer. It is recommended to use int main(). See here
2) You have made a system call, however forgot to include the necessary header files for the function (stblib.h). However, system calls are not recommended. See here

It is recommended to use a function like char get_grade(int marks) instead of repeating it

xavier666 56 Junior Poster

Hello Vijay,
Even though it's ok but it's using static memory allocation.

Anyways,
1) Correct me if i'm wrong, in the functions removeright & removeleft, shouldn't the error messages be "DEQUE UNDERFLOW"?
2) Line 71, it should be return 0 not return o :P
3) Use proper indentation
Thanks anyway...

PS don't bump old threads...

xavier666 56 Junior Poster

If that happens, and you overrun the boundaries of the first array, the second array gets unintentionally modified as well.

The thing is, i didn't even modify the first array, then how come the second array is modified?

int operator==(strings &obj)
        {
            if(strlen(strng) != strlen(obj.strng))  //  NO MODIFICATION
            {                                       //  ONLY READING
                return 0;
            }

            int i;
            
            for(i = 0; i < strlen(strng); i++)
            {
                if(strng[i] != obj.strng[i])        //  NO MODIFICATION HERE ALSO
                {
                    return 0;
                }
            }
                                                    //  NO MODIFICATION TILL HERE
                                                    //  WHEN I PRINTED THE STRINGS
                                                    //  HERE, THEY WERE FINE
            return 1;
        }

But inside main(), just after the function call, the string passed as parameter gets changed. So how the hell is this happening?
And why is the program correcting itself when I'm passing a reference of the object to the function?

xavier666 56 Junior Poster

The element "strng[length]" does not exist

Aww man! I generally don't make these mistakes. Dammit!

This is how it should look...

strings(const char * str)
        {
            int length = strlen(str);
            strng = new char[length + 1];

            int i;

            for(i = 0; i < length; i++)
            {
                strng[i] = str[i];
            }

            strng[length] = '\0';
        }

Thanks Ancient. It worked but why? What did I do wrong?

@dusktreader
I'm trying to make my own functions...

xavier666 56 Junior Poster

I would suggest you to read the chapter on pointers from your text-book before asking such questions here. These topics are covered in any standard books...
Here is the syntax...

#include <iostream>
using namespace std;

void func(int array[]);

int main()
{
      int array[] = {10,20,30,40};
      func(array);
      //    func(&(array[0]));  //  AN ALTERNATIVE MENTHOD OF SENDING
      cin.get();
      return 0;      //  IT'S GOOD TO SEE BEGINNERS USE int main() INSTEAD
}                    //  OF void main(). GJ!

void func(int *array)
{
     cout << array[1];
     //     cout << *(array + 1);   //  AN ALTERNATIVE MENTHOD OF PRINTING
}
xavier666 56 Junior Poster

Okay this program is really pissing me off! After line 95, the member variable is suddenly getting changed (That is, the 2nd string). Even after looking at it for 3 hours, I've failed to crack it :(
Please help me out guys!

# include <iostream>
# include <cstring>
using namespace std;

class strings
{
    private :
        char *strng;

    public  :
        strings(const char * str)
        {
            int length = strlen(str);
            strng = new char[length];

            int i;

            for(i = 0; i < length; i++)
            {
                strng[i] = str[i];
            }

            strng[length] = '\0';
        }

        ~strings()
        {
            delete(strng);
            strng = NULL;
        }

        void string_show()
        {
            cout << strng;
        }

        int string_length()
        {
            return strlen(strng);
        }

        int operator==(strings obj)
        {
            if(strlen(strng) != strlen(obj.strng))
            {
                cout << "\n\n\t* INSIDE FUNCTION!";
                cout << "\n\n\t" << strng;
                cout << "\n\n\t" << obj.strng;
                return 0;
            }

            int i;
            for(i = 0; i < strlen(strng); i++)
            {
                if(strng[i] != obj.strng[i])
                {
                    cout << "\n\n\t** INSIDE FUNCTION!";
                    cout << "\n\n\t" << strng;
                    cout << "\n\n\t" << obj.strng;
                    return 0;
                }
            }

            cout << "\n\n\t*** INSIDE FUNCTION!";
            cout << "\n\n\t" << strng;
            cout << "\n\n\t" << obj.strng;

            return 1;
            
            //  **UPTO HERE, THE STRING IS NOT CHANGED!!**
        }

};

int main()
{
    strings obj_1("Hello");
    strings obj_2("Hello");

    cout << "\n\n\t1st String : ";
    obj_1.string_show();
    cout << "\n\n\t2nd String : ";
    obj_2.string_show();

    cout << "\n\n\tLength Of 1st String : " << obj_1.string_length();
    cout << "\n\n\tLength Of 2nd String : " << obj_2.string_length();

    cout << "\n\n\t1st String ~ Length : " << obj_1.string_length() …
xavier666 56 Junior Poster

its so easy!!!!

It's the I-know-the-answer-but-I-won't-tell syndrome.
It generally happens to people who suffer from I-don't-know-the-answer

Don't be too hard on him...

xavier666 56 Junior Poster

Are you talking about this?

class LinkedList
{
    protected :
        int data;
        LinkedList * link;
    public :
        virtual void store(int n) = 0;
        virtual int  retrieve()   = 0;
};

class Stack : public LinkedList
{
    public :
        void store(int n)
        {
            Stack * new_add = new Stack;  //  THIS STEP IS STILL
            new_add -> data = n;          //  GIVING ME ERROR
            new_add -> link = NULL;

            if(link == NULL)
            {
                link = new_add;
            }
            else
            {
                ...
            }
        }
};

This is not working. And I think it's not working because it's not the invoked object (Like you said!). I can only access protected members of invoked objects. It's giving me this error error: `int LinkedList::data' is protected

xavier666 56 Junior Poster

Can you please provide us with the code?

xavier666 56 Junior Poster

Okay Mike, I got what you said. I raised this question because I got an assignment which i think, is related to this. Check this out.

  1. Create a generic base class called LinkedList for integer values
  2. It stores pointer to list and integer value
  3. It also declares two pure virtual functions, store() and retrieve()
  4. Create two derived classes called Stack and SortedList (in ascending order) that inherit from LinkedList
  5. Write a main() function to create a stack of integers and a sorted list of integers

Now see point 2, it says that the class contains a self-referential pointer and an integer data. Or in other words

class LinkedList
{
    protected :
        int data;
        LinkedList * link;
    
    public    :
        virtual void store    ( int number ) = 0;  //    According to point 3
        virtual int  retrieve ( void       ) = 0;
};

But class Stack and class SortedList will override the inherited functions of LinkedList
Then let us consider only one case, the case of class Stack

  • I'll first override the function store() of class Stack
  • Since, an object of this class will act as the ADT Stack, the function store() will act as the function push()
  • But the stack will be implemented as a linked list
  • Hence, i will create node, put data in node and then link it. But there is a problem
  • As i have to create a node, it should be of type LinkedList and not Stack, because the variables are of …
xavier666 56 Junior Poster

Damn! Mike was too fast.
Nice one mike_2000_17!

xavier666 56 Junior Poster

Well, I'm a noobie but when I have to send an entire structure array, I just send the pointer to the 1st position of the array. Here is a sample code

# include <iostream>
using namespace std;

typedef struct AA
{
    int a;
}A;

void print (A *struc_point)
{
    cout << struc_point -> a << "\n";
}

int main()
{
    int i;
    A new_struc[5];

    new_struc[0].a = 1;             //  GIVING SOME RANDOM DATA
    new_struc[1].a = 2;
    new_struc[2].a = 3;
    new_struc[3].a = 4;
    new_struc[4].a = 5;

    A *pointer = &(new_struc[0]);   //  PUTTING THE ADDRESS OF THE
                                    //  1ST STRUCTURE VARIABLE IN 'pointer'

    for(i = 0; i < 5; i++)
    {
        print(pointer);
        pointer ++;                 //  GOING TO THE NEXT STRUCTURE VARIABLE
    }

    return 0;
}
xavier666 56 Junior Poster

Wow! You're so close! Just fill in the last two functions and you're done. Then you'll see that you don't even need our help.

You also need to attach the ass1.h file to your post and give proper code tags...

xavier666 56 Junior Poster

Here is a very simple code demonstrating how 'protected' is used

# include <iostream>
using namespace std;

class A
{
        protected :
                int a;
};

class B : public A
{
        public :

                void f_1()          //    *
                {
                        a = 10;
                        cout << a;
                }
};

int main()
{
        B obj_2;
        obj_2.f_1();    //    **

        return 0;
}

*This function here, f_1(), puts the value 10 inside the variable 'a' of object obj_2 present here **. That is, it changes the value of 'a' of the invoking object

But mind you, 'a' is inherited as it is protected in the base class 'A'

But if I change my program to this, that is, only change the function f_1() to this

# include <iostream>
using namespace std;

class A
{
        protected :
                int a;
};

class B : public A
{
        public :

                void f_1()
                {
                        A obj;          //    This part changed!!
                        obj.a = 20;     //    Made a seperate object,
                        cout << obj.a;  //    instead of using the invoked object
                }
};

int main()
{
        B obj_2;
        obj_2.f_1();

        return 0;
}

Then it gives this error error: `int A::a' is protected So can someone please explaing why this error is occuring?

xavier666 56 Junior Poster
#include<conio.h>

This code hurts :O

I tried but could not find any other mistake which could have caused runtime error.. Can you please help!!

We here will not directly give you the answer. Check again. You'll find the error...
Give us the new corrected code...

xavier666 56 Junior Poster

Dave,
Will be really missing you.
Whenever I saw that Dave has replied to my post, it meant that my query has been solved. It's a shame that I couldn't know you better. All I know that you were a gifted programmer and a true gentleman, always polite and full of patience.
In a programmers language ~ </life>

xavier666 56 Junior Poster

I agree Acrimonus, but it is assumed that before a new user posts, he or she has read the forum rules. But even after such precautionary measures, if the user commits such a mistake, he's bound to get jumped upon.
And these guys are losing patience after seeing such posts cropping up daily. Even I was chided during my first visit here :)

xavier666 56 Junior Poster

You know what, one could start a Hall Of Fame for such posts like Bash
We could show the new users what type of posts not to make.

xavier666 56 Junior Poster

I fail to see how this is difficult

Actually, I just couldn't understand the question.
All I know about rational numbers is that they are Set of Real Numbers minus Set of Irrational Numbers Or another way of defining them is "Any number that can be expressed in p/q format where q≠0 (p & q belong to set of integers)"
But I don't know how to express them as an ADT

xavier666 56 Junior Poster

I've come across two questions from my previous years college test papers. I just couldn't solve them

  1. Define rational number as an ADT (abstract data structure)
  2. Write a suitable C code to sort a finite set of elements where an element may appear a large number of times

For the second question, only the logic would suffice
Thanks in advance!

xavier666 56 Junior Poster

- is the instructor's pet compiler because he's a hack

What did you mean by 'he's a hack'?

xavier666 56 Junior Poster

Do you know this feature of characters in C?

char ch = 'A';
ch = ch + 1;
printf("%c", ch);

Output

B

Now, you said ASCII code of 'A' = 65 & ASCII code of 'a' = 90, hence try to figure how much you should add/subtract from a character to convert into uppercase/lowercase

xavier666 56 Junior Poster

Okay, here is my last problem in this thread. Sorry for wasting your time like this.
It's related to code blocks. Now i generally do stand alone programs, that is, i don't include them in projects. So, then how do force the compiler to compile my files in C instead of C++?

xavier666 56 Junior Poster

Aww c**p! Forgot to give those teeny weeny things. Should it be like this?

# include <stdio.h>
# include <stdlib.h>    //<-------------STDLIB.H---------------
 
int main()
{
    int * element = malloc(sizeof(int));
    int * array   = calloc(5,sizeof(int));
 
    *element = 5;
 
    printf("ELEMENT - %d", *element);
 
    free(element);
    free(array);
 
    return EXIT_SUCCESS;
}

Slipped outta my mind that element is a pointer

xavier666 56 Junior Poster

Here is the code...

# include <stdio.h>
# include <stdlib.h>    //<-------------STDLIB.H---------------

int main()
{
    int * element = malloc(sizeof(int));
    int * array   = calloc(5,sizeof(int));

    element = 5;

    printf("ELEMENT - %d", element);

    free(element);
    free(array);

    return EXIT_SUCCESS;
}

And I've attached my stdlib.h

xavier666 56 Junior Poster

>Is there like a source code or anything for it?
Obviously there is a source code but you have to figure it out. Just follow the tips Vernon has given and you should do fine. If you are still uncomfortable, can you print this triangle?

*
**
***
****
*****

If you can, then your original problem is just a modification of this one. Just think about this...
If you can't, then pursue this one first.

xavier666 56 Junior Poster

You might wanna mark this thread as solved...

xavier666 56 Junior Poster

Are you trying to do something like this?

Enter The Number - 7

7 % 2 = 1
7 % 3 = 1
7 % 4 = 3
7 % 5 = 2
7 % 6 = 1

Your for loop is a bit faulty. If you can correct that, the program will run fine. Here is a cryptic hint; you have to remove something from the for loop. Then it'll run.

PS - This method of checking prime numbers is a bit time consuming.

xavier666 56 Junior Poster

Are you trying something like this?

*
  ***
 *****
*******
xavier666 56 Junior Poster

OMG! Here comes my "Turbo-C-Knee-jerk"
I see you are using an outdated compiler. When we copy and paste your program in our compiler (unless someone has Turbo C), it won't run because your program uses outdated header files (conio.h)

I suggest you get Code::Blocks

Now, technically speaking, what you have done is not a linked list, but simply a list. You have not done the delete function. For an array, you have to shift all of the elements to one side. But for a linked list, deletion is very easy. Since you have asked for a linked version of the phone book problem, could you show us the linked list version, even if it's incomplete?

PS - Try to avoid using global variables

xavier666 56 Junior Poster

What have you done so far? Could you show us that?

xavier666 56 Junior Poster

Turbo C/C++ has EVERYTHING already laid out for her, in the help file - with example programs of EVERYTHING she has to do

Then people might become more susceptible to the ..uh.. "copy-pasting" disease

Does CODE:Blocks even have graphics? Turbo does.

No, seriously. Didn't know about all this. Will most probably start next semester. Was about to uninstall it.

xavier666 56 Junior Poster

Yes, for the N'th time, i am including stdlib.h

xavier666 56 Junior Poster

@aianne
I would recommend you scrap that compiler (which supports non-standard header files) and get yourself a new one that supports C99
I would recommend Code::Blocks.

xavier666 56 Junior Poster

Did it. But just a little improvement. No errors but warnings instead.

||In function `main':|
|9|warning: assignment makes pointer from integer without a cast|
|11|warning: int format, pointer arg (arg 2)|
||=== Build finished: 0 errors, 2 warnings ===|

Woe is me!

xavier666 56 Junior Poster

If you return 0 from main and the system thinks your program is returning an error then you are using a non-conforming compiler and should think about changing it.

You mean to say that return 0 means, by default, success (irrespective of platform). Hurray!
So, does all this means return EXIT_SUCCESS is redundant?

xavier666 56 Junior Poster

I didn't get you "the implementation must convert it..."
Since I don't know on what platform I'm working in, how would i know when to convert and when not to convert the return value?

xavier666 56 Junior Poster

Uh... how would I do that in Code::Blocks?

xavier666 56 Junior Poster

Currently, i was assigned to create an array, which i have no idea what array is.

Oh come on! Then I (along with several others) would suggest you to read your C Programming book before diving into such problems

WaltP commented: Thank you for beating me to this thread! +11
xavier666 56 Junior Poster

I don't believe there is any standard method for reducing the text size.

This is the crux of the problem. You cannot view more than 50 lines at a time in DOS mode (as far as i know). But there is a trick. It involves pausing the screen after every 50 outputs. The algorithm is something like this

FOR LOOP ( START = 1 | END : WHEN START =  250 | INCREMENT START )
{    
    PRINT (VALUE OF START)
    IF (START IS A MULTIPLE OF 50)
    {
        PAUSE
    }
}

Convert this to code and i think you'll do fine ...

Or try this but I'm not sure whether this will work or not
Go to cmd, right click, properties -> options tab -> buffer size. Set it to 250. Set it for future use. Then try to run your program. Let me know of the results

xavier666 56 Junior Poster

I just heard from a source that some systems treat return 0 as a "function gone wrong". So to avoid platform dependencies, one should use return EXIT_SUCCESS Is this all correct?

xavier666 56 Junior Poster

it's about binary trees but we'll use names instead of numbers or single chars

Can you make a binary tree using numbers or single characters?
If you can, post that attempt.
If you can't, you have to go back to square one and read the theory first.

tux4life commented: :) +8
xavier666 56 Junior Poster

I hate bringing up old threads but I was thinking about this but did not have the courage of asking a MOD but this seems like a good opportunity. So, can i make a list of Common malpractices of C?

xavier666 56 Junior Poster

Set value of i to zero int i = 0; and put fgets(s,sizeof(s),stdin) instead of using getchar() This program is running fine in my compiler with those two modifications

xavier666 56 Junior Poster

In your program when you use malloc, you are allotting space for just one integer, which I think is not what you want to do... If you want to allot space for an array of 5 integers via malloc the correct syntax is

I was just showing that my compiler was flagging both of the statements as errors.
I know malloc(N * sizeof(TYPE)) = calloc(N, sizeof(TYPE)) but when there is a dedicated function for multiple allocation, why not use it.
Go through this one. You'll know what Banfa means.

I wish someone could tell me how to force my compiler to compile in C mode instead of C++

xavier666 56 Junior Poster

You might wanna see that in LINE # 20 & 21, you messed up the comments. It should be like this

printf("%s\n", s); /*Testing the string was infact inputted*/
for (i = 0; c != '\0'; i++)/*Traverses the character string until EOF*/

I was just thinking, can we give more than one newline during input using stdin

xavier666 56 Junior Poster

Here is the file. Name of the file is "memory.c".
http://img28.imageshack.us/img28/4342/memoryc.jpg
There is an attached image for confirmation
I have given stdlib.h Line # 6 & 7 are flaged as errors in HOME COMPILER but as warnings in COLLEGE COMPILER

HOME COMPILER
1) CODE::BLOCKS 8.02 Using GNU GCC Compiler
http://img338.imageshack.us/img338/6487/compiler.jpg
2) XP SP2

COLLEGE COMPILER
1) LINUX - RED HAT
2) Using SSH Client. It's a CUI environment

# include <stdio.h>
# include <stdlib.h>    //<-------------STDLIB.H---------------

int main()
{
    int * element = malloc(sizeof(int));
    int * array   = calloc(5,sizeof(int));

    free(element);
    free(array);

    return EXIT_SUCCESS;
}
xavier666 56 Junior Poster

After you malloc space, you should check if you actually got space or not. That could be one of the reasons for your error

I keep forgetting to put that check after allocation but no, that was not the cause for error. See my above post ...