Monday, May 24, 2010

I think I'm misunderstanding this line of code in C++?

What does this line do?





int* addr = new int[num];





It is making an array with a pointer? Or something? I've been studying for a final and doing my last programs in a class all day and the code is starting to blend together...

I think I'm misunderstanding this line of code in C++?
addr is a pointer to an array of num ints





This lets your program dynamically allocate the memory for the array, instead of having a fixed amount of memory by defining int a[1000], for example. You can't say int a[num]; it's not valid.





You use this when you'll be determining the size of the array programmically. It's then also common to see delete a[ ] later on to free the memory.





Check out this site:


http://www.fredosaurus.com/notes-cpp/new...
Reply:It creates a new array of num integers, and sets addr to the address if the first element of the array.


How can i go backwards in a character buffer in 'C'?

for example...if i hav to search for a "//" in a buff...


{


//asnbvfv hjegfub hgdyfgh cjs


}


and if my pointer is pointing to cjs.... how can i get back to //...???


thanx in advance

How can i go backwards in a character buffer in 'C'?
Decrease the value of the pointer (for example, by using the -- operator) and it will go to the left. Increase it and it will go to the right.
Reply:decrement your pointer-- and it will move back one char,


then check the dereferenced char value of where it's pointing now and the place it was pointing





do{


pointer--;


}


until ("/" == pointer[0] %26amp;%26amp; "/" == pointer[1] )





something like that, don't lock it up in some infinite loop...
Reply:Yes, you can decrement and increment the pointer as much as you want, provided the buffer still contains the characters, i.e. if they haven't been popped off a stack or something similar. In the case you're describing, you can simply set the pointer offset to zero to access the first character.





But perhaps you mean you're getting characters one by one from the keyboard or a file and want to go back and look at previous characters? In that case, as they come in send the characters to your own buffer which you can examine at will.





Bear in mind that pointer arithmetic is always a minefield and indexing something outside a buffer's valid range is a very common error.


Am trying to trace a quote by an old "preacher" - C M Lochridge {?} "This is my King"?

A pointer to a web site or such would be appreciated.


This could be circa1950's

Am trying to trace a quote by an old "preacher" - C M Lochridge {?} "This is my King"?
S. M. Lockridge - Awesome!





http://www.ignitermedia.com/products/iv/...
Reply:Took a bit, but it's SM Lochridge. Here are the google results:





http://www.google.ca/search?hl=en%26amp;client...





Enjoy!
Reply:Dr. S. M. Lochridge


How do you declare an array in a structure in C?

Is this right?





typedef struct listStruct


{


char word[20];


int counter;





pointer ptr;


} list;

How do you declare an array in a structure in C?
That works. If you don't know how large the array will be, you could also use "char*" (a pointer), and then later use malloc() to get memory for the array (as in "word = (char*)malloc(NumOfCharacters*sizeof(cha... As you have it written, you just need to make sure never to try to put 21 characters in the array. :)
Reply:yes its right 10/10

magnolia

How to fill an array in a function with c++?

how to pass the parameters?


is there any other way without pointer and please help me because I need a function that fill an array

How to fill an array in a function with c++?
Pass it normally, using the correct declaration. That is, if you had char someVar[], pass it to the function as char functionVar[]. Then treat the function argument as you would the real array.





%26gt; is there any other way without pointer


Read http://c-faq.com/aryptr/index.html . There's an equivalence between pointers and arrays in some cases, so that's why you can work with the formal argument like you would with a pointer. Go through the C FAQ I linked to. It's confusing, and takes time to digest.





If you really want to understand C++, you should get a serious book. For C++, it's C++ Primer by Lippman or Accelerated C++ by Koenig (both are suitable for beginners). To understand the C portion of C++, you may want to get yourself K%26amp;R's The C Programming Language.
Reply:you can't modify an array if you pass by value into a function you have to pass by referance. When you pass by value a copy of the array(or any object) is put on the stack( or heap) . The keyword here is copy. I'm sry but you have to pass by reference otherwise you break the rules of encapsulation.


How to convert byte into string in c language?

i m having pointer so structure which members are of BYTE type.........i want to convert them into string(to print vendor name) and into number(to print serial number).....how to do it...i m using vc++........

How to convert byte into string in c language?
Byte is equivelant to unsigned char in C++ with values (in binary) from 0000 0000 to 1111 1111. To convery byte into a string you would end up with a single unsigned char (simply by typecasting it). Not the ideal way to do this.
Reply:I don't understand what you mean. Is each letter a character type? Do you need to transfer that into one string? Or is it an array of bytes?


Why would you use reinterpret_cast in c++?

I think it's used to convert a pointer of one type to another by performing a "binary copy". What does that mean and why would you ever want to do that?

Why would you use reinterpret_cast in c++?
The reinterpret cast converts one pointer type to another. It does not perform a binary copy of the object.





Its best use is to convert a base pointer to a class back to the derived class type. for example:





class A


{


};





class B: public A


{


public:


int m_nVar;


};





// base pointer pointing to derived class


// has no access to m_nVar


A *aPtr = new B;





// cast base pointer back to derived class pointer


// has access to m_nVar


B *bPtr = reinterpret_cast%26lt;B%26gt;(aPtr);





You can also use it to cast char* to int*, or any other number of unsafe converstions, but this is not recommended.


How to give tooltip to class properties in C# like Intellisence?

In .Net IDE We have Intellisence facility which will give automatically class methods and properties etc when we press dot(.) operator. While moving the mouse pointer on class properties or function names we will get help text about that properties. How can I give the help text to my class properties and functions.

How to give tooltip to class properties in C# like Intellisence?
You use XML comments. Basically, XML comments are tags that you put before methods, classes, etc... We enter these XML comments after a triple backslash.





Here is an example:





///%26lt;summary%26gt;A funtion that does something.%26lt;/summary%26gt;


///%26lt;param name="i"%26gt;I is some int...%26lt;/param%26gt;


///%26lt;param name="input"%26gt;Input is some string...%26lt;/param%26gt;


///%26lt;returns%26gt;Returns an int%26lt;/returns%26gt;


int DoStuff(string input, int i) {


...


}





For more info on XML comments and what tags are available, go here: http://msdn.microsoft.com/library/en-us/...

forsythia

How do I delete a vector in c++?

I want to delete the whole vector and everything inside it. I tried "delete ListViewText;" But I got this error:


error: type `class std::vector%26lt;std::string, std::allocator%26lt;std::string%26gt; %26gt;' argument given to `delete', expected pointer

How do I delete a vector in c++?
you can delete a vector only if you allocated it with "new"
Reply:either use delete operator if u have created it using new


or to clear the vector use clear function provide by vector
Reply:It sounds like you want to remove all the items inside the vector. In that case, use the clear method:





vector.clear();





There is also a "remove" method if you want to remove only specific ranges of the vector.


Can you write a "split" function in C?

I blew an interview because I screwed up my pointer arithmetic while parsing a string:





Here is the syntax:





prompt%26gt;./split "This Is an input string" " "





output:


This


is


an


input


string





or:


prompt%26gt;./split "This is an input string" "p"


output:


this is an in


ut string





I tried putting '\0' wherever the split character occurred, but I couldn't turn it into an array of substrings.





Any ideas?

Can you write a "split" function in C?
Only strlen, strcpy, and strcat, eh? That's pretty harsh. I think you have the right idea putting '\0' at the split points. Instead of creating an array of substrings, though, create an array of pointers to the substrings.





Pseudocode:





char *s points to your input string


S is an array of pointers to char


char *p declared to walk through the input string


initialize p = s, i = 0





do {


set S[i++] = p


set p to next split point


set *p = '\0'


p = p + 1


} until last substring found





How about that? You don't even need any of those string.h functions!
Reply:And you weren't allowed to use strtok?


How can i write this program in c?

A program like a phonebook of a cellphone, using linked-list, a double pointer, sort it by name, the user will have the choice to edit or delete an entry and save it in a binary file and get it again.

How can i write this program in c?
Hey


Create a structure with fields like Name, Phone Number, E-Mail, Fax (In my cell phone, i have these options).


Two pointers of type this structure. One to connect to next node and one to connect to previous node.


For more information and implementation of double linked list, view the following


http://www.daniweb.com/code/snippet94.ht...
Reply:Modules:





Linked List


Sorting


Save/Load File


User Interface that uses the above three modules





Write each one individually and test them before gluing them together.


Designing a Binary Search Tree in C++ ?

Design a class template Table as the table to store the information of the people and another class Person to represent each individual person of the people in a table. The data structure of a table is the pointer-based binary search tree (BST). A table of people is an object of the class Table. The information of each person is store in a node, which is an object of the class Person. A relational database is conceptually a collection of tables (files). A table is abstractly a collection of to records (attributes).The information of a person consists of her (his) name, sex (male or female), birthday, address, city and phone number. Assume the names of the people are unique. The search key is the person’s name. Our program should be able to save a table for use later. We should be able to retrieve the information of a subgroup of people based on a given criterion. I need Add , Print , Delete and Save functions.

Designing a Binary Search Tree in C++ ?
Yeah, please leave Computer Science. You'll never be any good at it, since you don't do your own work. The world doesn't need people like you writing software for Air Traffic Control, radiation therapy machines, or even financial institutions. Do us all a favor and become a hair stylist. The worst that will happen there is that you give someone a bad haircut.
Reply:Do your own homework... your not asking a question your asking someone to do it all for you...

jasmine

Can anyone help me with a C program(no of days b/w dates) urgent.....??

Program is to find no. of days between 2 dates using pointer to structures

Can anyone help me with a C program(no of days b/w dates) urgent.....??
You can create simple date structure like that





struct date


{


int day;


int month;


int year;


};





void main()


{


struct date *d1, *d2;


d1-%26gt;day=10;


d1-%26gt;month=4;


d1-%26gt;year=1998;





//Similary you can declare d2 and so on and implement you code accrdingly





}








you can also visit my blog http://codesbyshariq.blogspot.com for more C, C++ programs


HOMONYMS : Can you figure out w/c part of the human body that each clue below represents?

%26gt; An accusing pointer


%26gt; pumping stations

HOMONYMS : Can you figure out w/c part of the human body that each clue below represents?
finger?


hearts?





These aren't homonyms which are words that sound alike, but have different meanings.
Reply:index finger





heart
Reply:um...your index finger and your heart?
Reply:index finger





gluteous maximus
Reply:Finger %26amp; heart valves
Reply:1 FORE finger 2 the HEART
Reply:#1 Index finger





#2. Heart
Reply:1) Index finger


2) Heart
Reply:index finger and heart are obvious answers, but do you really mean homonyms? or is this some kind of brit rhyming slang?
Reply:I dont know about the first, but could a pumping station be your mouth??


I need a hint on a c program?

#include %26lt;stdio.h%26gt;








int main(void)


{


FILE *reportfile;





reportfile = fopen("E:\\report.txt","wt");


if (reportfile = NULL)


{


printf("Report file open failed");


fflush(stdin);


printf("press any ");


}


else


{


printf ("hello are you working");


}


return 0;








}


This code is only a piece of my program if you need the whole program let me know. My question is the following i need to write the output to a file not to screen shots. This is what i am doing right now and i am opening the file correctly but i am not sending any output to the file what do i need to use to send the output to the file. And what about if i want to use i function can show help with both questions one without a function and the other one with the function calling the file as a pointer.

I need a hint on a c program?
look at fprintf. Probably that is what you are looking for since you use fopen.





If you use open instead, look at write.
Reply:visit by blog





http://codesbyshariq.blogspot.com for more hints.
Reply:I don't understand your last sentence, but if you want to write to a file using a FILE *, try fwrite().
Reply:#include %26lt;stdio.h%26gt;





int main(void)


{


FILE *reportfile;





reportfile = fopen("E:\\report.txt","wt");


if (reportfile = NULL)


{


printf("Report file open failed");


fflush(stdin);


printf("press any ");


}


else


{


// the next line sends output to the open file referenced by reportfile


fprintf (reportfile, "hello are you working\n");


fclose(reportfile); // Must close file when finished with it.


}


return 0;


}


How to create a dictionary using C++ programming language?

need to use file, class, pointer

How to create a dictionary using C++ programming language?
___________





// Here is some skeleton code; you can flesh out the specifics:





#include%26lt;iostream%26gt;


#include%26lt;fstream%26gt;


#include%26lt;string%26gt;





using namespace std;





class Dictionary


{


private:





char alphabet;


string meaning;


string word;





public:





void getmeaning(std::string *p);





void search()


{


string word;





cout%26lt;%26lt;"enter a word :";


cin%26gt;%26gt;word;





getmeaning(%26amp;word);


}


}di;











void Dictionary::getmeaning(std::string *p)


{


string a,b;





// Assume there exists a dictionary dic.txt


// Remember to add proper error handling (file operation)


ifstream get("dic.txt",ios::in);





while ( !get.eof())


{


get%26gt;%26gt;a%26gt;%26gt;b;





if (*p==a){


cout%26lt;%26lt;a%26lt;%26lt;" "%26lt;%26lt;b;


}


}


}











int main(){


int ch;








cout%26lt;%26lt;"=D=I=C=T="%26lt;%26lt;endl;


cout%26lt;%26lt;"1.Show meaning"%26lt;%26lt;endl;


cout%26lt;%26lt;"2.Show word"%26lt;%26lt;endl;


cout%26lt;%26lt;"3.Exit"%26lt;%26lt;endl;


cin%26gt;%26gt;ch;





switch(ch)


{


case 1:


di.search();





break;


case 2:


string word;





cout%26lt;%26lt;"enter a word :";


cin%26gt;%26gt;word;





di.getmeaning(word);





break;


case 3 :


return 0;


}


___________





EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT


___________





What is a Map?





The map container class provides the programmer with a convenient way to store and retrieve data pairs consisting of a key and an associated value. Each key is associated with one value. (If you want to associate a key with more than one value, look up the multimap container class.)








A working C++ dictionary program. It makes use of the Find() function:





Description: http://cis.stvincent.edu/html/tutorials/...





Code: http://cis.stvincent.edu/html/tutorials/...








Note: don't forget to include code in case the user enters a search word that is not in the dictionary.





___________

crab apple

I need a little help in c++?

my first question is ::


1.why we use "*"(asterisk) when we declare variables of type pointer???


and the second one is ::


2.the output of this code is "value 1==10 / value2==20" could u tell me why? am a little bit confused.


int value1 = 5, value2 = 15;


int * mypointer;


mypointer = %26amp;value1;


*mypointer = 10;


mypointer = %26amp;value2;


*mypointer = 20;


cout %26lt;%26lt; "value1==" %26lt;%26lt; value1 %26lt;%26lt; "/ value2==" %26lt;%26lt; value2;


return 0;

I need a little help in c++?
* is dereferncing operator thing of letter which has address, *letter is content of the letter


== is assignment operator.


You may also contact a C expert to help you speeden up learning. Check websites like http://askexpert.info/
Reply:The asterisk indicates that you are declaring a pointer.


A pointer is just a 32-bit number that indicates a memory location.


If you omit the asterisk in %26lt;int * mypointer;%26gt; you will be declaring the variable of type integer, not its address.





The reason why you get that output is simple. Here is step by step.


Firs, you assign the values for value1 and value2 in this line:


int value1 = 5, value2 = 15;


Then you get the addres where value1 is stored and you save it with the pointer in this line:


mypointer = %26amp;value1; %26amp; means that you are getting the address, not the value.


After that you change the value stored in that address in this line:


*mypointer = 10; Actually you are changin the value of value1 not mypointer. * before mypointer indicates that you want to change the value.


The same goes for value2.


And that's why you get your output.
Reply:What you are asking is a complex(for a novice person) topic. I don;t think I could explain accuartely what you are asking for. I do however know of an excellent website that can explain it to you.





http://www.sparknotes.com/cs/pointers/wh...





Good Luck and feel free to email me with any more questions


Need Help in making this c++ program?

Implement and thoroughly test a class named IVector that represents a


dynamic array of integers. It will have 3 private data members: int


capacity, int count, and int * items. The 'capacity' is the physical


size of the dynamic array (its actual number of elements). The 'count'


is the number of elements currently in use (indices 0, 1, ...,


count-1). The pointer 'items' points to the first element of the


dynamic array, which will be created by the operator 'new'.





Class IVector will have three constructors: 1) a default constructor


that creates an array of capacity = 2 and count = 0; 2) a constructor


with parameter int cap that creates an array of capacity = cap and


count = 0; and 3) a copy constructor with parameter "const IVector %26amp; V"


that creates an array that is identical to IVector V.





Class IVector will have the following public member functions: 1) two


getters that return the capacity and the count of an IVector object;


2) one declared "void Append( int item )" that adds 'item' to 'items'


at position 'count' and increments 'count' by one; 3) one declared


"void Insert( int index, int item ) "that adds 'item' to 'items' at


position 'index' and increments 'count' by one; and one declared "void


Delete( int index )" that deletes the item at position 'index' and


decrements 'count' by one.





Overload the operator '[ ]' to access elements of the vector by


subscript.

Need Help in making this c++ program?
What is the question?
Reply:Sounds pretty straightforward to me. So do you always get your homework done this way? Explains a lot about the state of the Software Industry.....
Reply:Does not look easy. May be you can contact a C++ expert at websites like http://askexpert.info/


I can not open my C or D drive with double click i have right click open to work, No errors shown?

When I double click any drive icon in my computer the pointer icon turns to busy icon but after few seconds it becomes normal but the drives can not open. I have to right click on drive and click open. Once the drive is open then I can double click on folders and work normally only the drives doesnt work

I can not open my C or D drive with double click i have right click open to work, No errors shown?
happended to me once your computer has a virus in it. If u look closely u will see that in the right click options u would also be getting an option for Auto Play. Now that should definitely no be there on local disk partitions. Try installing an Anti Virus. I suggest Nod32 u can get it here. Its a trial version but with full features and updates i used it to fix my computer when i had this problem.





http://www.eset.com/
Reply:There is this so called software that repairs Disk Drive errors which is infected by the virus FS6519.dll.vbs. Even though your anti virus had already deleted the virus. It still sits on your registry. You can use Disk heal to fix disk drive system info corruption. (Disk Heal is free) Report It

Reply:yes, It just happens some times.
Reply:you have some form of a virus or trojan...


Read text from Console in C++ ?

Please i need the code to read a text any text from the console.


reading as string or pointer of array.


for example how can i read "Hello"


notice that user can enter any text so the could should read any string text the user entered....even i don't know what tayp should i use

Read text from Console in C++ ?
// reading a text file


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


#include %26lt;string%26gt;


using namespace std;





int main () {


string line;


ifstream myfile ("the path of the .txt file");


if (myfile.is_open())


{


while (! myfile.eof() )


{


getline (myfile,line);


cout %26lt;%26lt; line %26lt;%26lt; endl;


}


myfile.close();


}





else cout %26lt;%26lt; "Unable to open file";





return 0;


}

strawberry

How can i make one c++ program read the virtual memory of another?

This is my problem...i need to use 2 matrixes, for fast information channels...in my algorithm. I can declare one of them in a program. If i declare both, then the program crashed (apparently due to some windows xp mem limit per program. When i declare 1 matrix in one program, but another in another program, and try to run both...i just get an error message saying that my page file is too small...so if i run this on a better computer, i'd be able to declare both matricies at once from two places. Now, i need to make the first program communicate with the second.


I want the first program to declare a matrix/array...get the memory address for the first element of the array, and length, and send that info through a text file to the other program...that would then take that number...load it into a pointer, and view the matrix without declaration. But this isn't working, why not?

How can i make one c++ program read the virtual memory of another?
There are a few ways that shared data can happen.





- create a RAM drive that has fast access. Then use both programs to open the same file. This is a GET IT DONE method.





- my second suggestion is what you have tried. But here is what might be wrong. Both programs have to be compiled, using the same compiler options. As I recall, if you use a LARGE scale object option, the pointers might work out universally. (the type of computer is not relavant).





- The other option is to install an ODBC text file or other global data structure. This could be an awesome and transportable method that would work on countless Windows computers of different flavors and environments. (Yet, I could not even begin to describe the programming details).





Good luck
Reply:I don't think you can just access shared memory on a whim, each modern program loads onto a computer in a separate memory space, the only way to communicate is through API calls, and memory addresses shouldn't be passed in them.





The other way is piping one program output into a master program but that is not going to solve your problem; in other words, without declaration is unlikely.


Need help fixing my C++ program.?

I need help getting my program to compile.





...


void rotate(Point%26amp; p, double angle)


{


double new_x = (((p.get_x()*cos(angle))


+(p.get_y()*sin(angle))));


double new_y = (((-(p.get_x())*sin(angle))


+(p.get_y()*cos(angle))));


double dx = new_x- p.get_x();


double dy = new_y- p.get_y();


p.move(dx,dy);


}


...


int main()


{





cout%26lt;%26lt; "The original point p (5,5) rotated 5 times by 10 degrees then scaled 5 times by .95 is:""\n";


Point p(5,5);


double angle = 10;


double scale = .95;


int rotation_count = 0;


int scale_count = 0;








while (rotation_count%26lt;5)


{


rotate(p, angle);





cout%26lt;%26lt; "The point is now " %26lt;%26lt; p.get_x %26lt;%26lt; "," %26lt;%26lt; p.get_x %26lt;%26lt; "\n";


rotation_count++;


}


...


This is the error I recieve


Error 1 error C3867: 'Point::get_x': function call missing argument list; use '%26amp;Point::get_x' to create a pointer to member d:\my documents\visual studio 2005\projects\a3q2\a3q2\assgn3q2.cpp 52





line 52 : cout%26lt;%26lt; "The point is now " %26lt;%26lt; p.get_x %26lt;%26lt; "," %26lt;%26lt; p.get_x %26lt;%26lt; "\n"

Need help fixing my C++ program.?
you forgot the parenthesis on the method calls:





line 52 : cout%26lt;%26lt; "The point is now " %26lt;%26lt; p.get_x %26lt;%26lt; "," %26lt;%26lt; p.get_x %26lt;%26lt; "\n"





should be:





line 52 : cout%26lt;%26lt; "The point is now " %26lt;%26lt; p.get_x() %26lt;%26lt; "," %26lt;%26lt; p.get_x() %26lt;%26lt; "\n"





-devon


Anyone good at C++? need quick help at least point me in the right direction?

Write a function that adds the elements of two 3-D arrays of size [n] [2] [2]. Create and initialize a 3-D array with n=2 where all of the elements are initialized to 2. Test the function by using it to add the array to itself. Next create a 3-D array with n= 3 where all of the elements are initialized to 3. Again test the function by using it to add the array to itself.





2: Write a function to print out the elements of arrays of size [n] [2] [2]. Use the function to print the results from the above two additions.





3: Write another function to add the elements of 3-D arrays of size [n] [2] [2], except use pointer arithmetic inside the function to implement the addition. Test the function.





I know how to create basic functions but as far as arrays, I have no clue even what arrays are. I just need guidance on this, i'm not asking anyone to do this problem. Code examples would be great though.

Anyone good at C++? need quick help at least point me in the right direction?
It's highly unlikely that your teacher would have given you an assignment which asks for three dimensional arrays without you having ever heard of them before. I would suggest listening in class, it'll do wonders.





Your teacher/professor will no doubt be more than happy to explain what an array is and how to use it, and will do a much better job than any online resource, so I would strongly suggest asking him or her. Nevertheless, here's a breif explanation:





Arrays are variables which store a set of values - for instance, an array of integers will let you store a set of integers all under one variable name, and then you access each individual item with [ ]. So for instance, once you've created and filled an array, you can access the first item in the list with 'varName[0]' and the second with 'varName[1]' and so on. Two dimensional arrays are an array of arrays, which you can visualize like a grid or table. And if, for instance, you wanted to access the second item in the third array, you'd say 'twoDArray[3][2]'.
Reply:You really need to just read the chapter on arrays in your text book. Arrays and pointers are fundamentals for the C++ language -- if you don't understand them you will fail at being able to master the language.
Reply:arrays are really a simple concept.


Arrays are basically a collection of variables which belong to the same data type.


for example this a integer array :: 1,34,54,3,45,56,67,34


and its size is eight ,since it has eight elements.


The above example is a one-dimensional array


syntax to declare a 1-dimentional array ::


%26lt;datatype%26gt; %26lt;variable name%26gt;[%26lt;size%26gt;]


example for an integer array :: int numbers[8];


example for a float array :: float numbers[8];


Now to Access a single element value in the array you can use the index number. for example if we take the array example above and use this line of code ::cout%26lt;%26lt;number[1];


the output will be 34. the elements position starts from 0 to n-1 n being the number of elements.





You can have multi dimensional arrays too.


suppose you want to represent a matrix then you can use a two dimentional array. 2 dim arrays will have two indexes like numbers[2][3]. This means the third element in the 2nd row.


Creating an array of structures within another strucure in C.?

i have an assignment that involves creating a Graph ADT. within this i need to have an array of Lists.





my List ADT is basically a doubly linked list with certain functionality. to create a new you call the function:





ListRef newList();





NOTE: ListRef is defined as "typedef struct List* ListRef". i.e., its just a handle/pointer to a List structure.





the problem is that you don't know the size of the graph until run time since you create a new one with the function:





GraphRef newGraph( int n );





where n is the number of vertexes in the graph (and thus the size of the array of List ADTs) and a GraphRef is just a pointer to a Graph structure.





i'm trying to do something like this:





struct Graph{


.


.


ListRef* list_array;


.


.


}





GraphRef newGraph( int n ){


GraphRef G = malloc(sizeof(Graph));


ListRef L[n];


.


.


for( i=0; i%26lt;n; ++i){


L[i] = newList();


}


G-%26gt;list_array = L;


.


.


}





But this results in no Lists being created (they are NULL) and then a core dump. what is wrong?

Creating an array of structures within another strucure in C.?
I think that the problem is that your ListRef array is being defined on the stack in the function newGraph(int n).





Once the function scope is over, G-%26gt;list_array will be pointing to a location that it doesn't own, and the first operation that it performs on it will cause a core dump.





What you need to do instead is to create your G-%26gt;list_array using malloc:





G-%26gt;list_array = (ListRef)malloc(n*sizeof(ListRef));





and then continue as before.





Hope this helps.





P.S. Interesting problem by the way :).

kudzu

An error in c++ code???????

i want to know where's the error?, this is a program that get the max element in an array by using a pointer on the beginning of it and another on the last element


#include%26lt;iostream%26gt;


using namespace std;


int main()


{


int arr[5]={4,8,3,2,5};


double *ist,*last;


max(* ist,*last);


}


double max(double *begin,double*end)


{


double r=,x=0,y=0;


for(int i=0;*begin[i]%26lt;=end;i++)


r=begin[i];


x=begin[i+1] ;


if(x%26gt;r)


{


y=x;


}


else


{


y=r;


}


return y;


}

An error in c++ code???????
You have to initialize the pointers, and you have an int array, but your max function takes double*. So you either have to make the max function take int* or change the int array to a double array.





Once you fix the data type problem, here is how you initialize the pointers:





ist = %26amp;arr[0];


last = %26amp;arr[4]; // The element in the array since it's zero based indexing


Strtok() prob in c?

#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





int main ()


{


char num[] ="1.00:2.00:3.00";


char *ch;


char r[100];


printf ("split \"%s\":\n",num);


ch = strtok (num,":");


while (ch != NULL)


{


i = 0;


printf ("%s\n",ch);


ch = %26amp;r[i];


ch = strtok (NULL, ":");


i ++;


}


return 0;


}








--%26gt; here is my strtok code, but it doesn't work.





how can i copy the values of the pointer ch into a char array r? thanks.

Strtok() prob in c?
1. need to add "int i = 0;" at the top and remove "i = 0;".


2. the printf is working fine.


3. strcpy(%26amp;r[i],ch); i += strlen(ch) + 1; instead of the last 3 lines in the llop


Word scrambler in C?

I'm trying to make code to scramble a word and it seems right, but everytime I call this function, the program crashes:








void scramble(char** word) // Pointer to (char* ) style string


{


......int length = strlen(*word);





......for(int i = 0; i %26lt; length; i++)


......{


............int rand1 = rand() % length;


............int rand2 = rand() % length;





............// Switch letters at rand1 and rand2


............char temp = (*word)[rand1];


............(*word)[rand1] = (*word)[rand2];


............(*word)[rand2] = temp;


......}


}

Word scrambler in C?
Good points by Steve T. above.





Your problem may be in how you're calling the function. I took your function, created main( ) as shown below, and the scramble function runs without crashing.





#include "stdio.h"


#include "stdlib.h"


#include "string.h"


#include "time.h"





#define MAX_WORD 256





void scramble(char** word);





int main(int argc, char *argv[]) {


char s[MAX_WORD];


char *word = s;


int done = 0;





srand(time(NULL));


do {


memset(s,0,MAX_WORD);


printf("\nEnter word (x to exit): ");


fgets(s,MAX_WORD,stdin);


*strchr(s,'\n') = '\0';


done = ((strlen(s) == 1) %26amp;%26amp; s[0] == 'x');


if (!done) {


printf("\n%s scrambled = ",s);


scramble(%26amp;word);


printf("%s\n",s);


}


} while (!done);





return 0;


}
Reply:What he said about the crashing, make sure your string is null-terminated.


Also, why do you need a pointer to a pointer (char**)? That seems a bit unnecessary since passing in a pointer would accomplish what you want it to (change the string you pass in and not make a copy of it).





As per your scrambling scheme it actually is suboptimal. One best way to scramble letters or anything is using the Fisher-Yates-Knuth shuffling algorithm (see sources). Essentially the problem with your shuffling scheme is that it shuffles too much in some spots and not enough in others. If you look at the source code for Fisher-Yates it will look awfully like yours but it does the shuffling in a specific order.





Also, for a more effective scrambler make sure you seed your random number (using srand). A common way to do it is to use the command "srand(time(NULL));" (you need to include time.h) though this isn't a terribly great solution. Only saying because I don't see it in your function.





Furthermore, if you are really, really concerned with randomness you might wanna look at your rand statements. When you say "rand() % length", functionally youre mapping all of the possible numbers from rand onto the numbers from [0,length-1]. However, since length doesn't divide the maximum possible rand number evenly (and since rand is a weak pseduo random number generator) your numbers will have a bias. In particular, smaller numbers would have a slightly higher chance of appearing than larger numbers. The wikipedia page discusses this as well.





http: //en . wiki pedia . org /wiki/ Fisher-Yates_shuffle





^Fill in the spaces for the above. I tried submitting this and yahoo gave an error since its from wikipedia.
Reply:The only thing that I can see that would cause your function to crash is the call to strlen(). It expects the string to be null-terminated, and will crash if it's not.





Make sure that the string you pass into this function has a null at the end.





The other thing you can do is put some printf() statements into your code at various places to see where it's crashing.


Help me with C programming?

Please help me create a program that does this.





Create a story that will have certain words (nouns, verbs, etc.) filled in by the user. You'll need to use gets() and the strcpy() functions to accomplish this. Be sure that your prompts are complete by asking for the type of word you're looking for and the tense (if necessary). Keep all words that are the same part of speech in an array of pointer. Values need not be randomized. Try to make a story that will be funny! J You should have at least ten words filled in by the user.

Help me with C programming?
This reminds me of an exercise in a book, is this some kind of homework a teacher has given you to do out of a book? IF so be honest about it and place this in homework section don't try and fool people otherwise some people wont be willing to help. Just get user input then copy that user input into another string and go from there Im not doing homework
Reply:i would have helped but im not as far as you in learning as I havn't went over strcpy() functions

garland flower

Error help for c++ beginner ... 10 points for the first correct answer!!!?

I am trying to make a hangman game, but i have one error remaining on compilation that i don't understand:


"error C2248: 'std::basic_ios%26lt;_Elem,_Traits%26gt;::basic_io... : cannot access private member declared in class 'std::basic_ios%26lt;_Elem,_Traits%26gt;'" The pointer to the error is not in the code i have written... it appears in the istream


... Please explain the error and how to fix it (detailed but simply)..... Thanks in advance!!

Error help for c++ beginner ... 10 points for the first correct answer!!!?
Would have to see the code in order to tell you how to fix but it the error isn't in iostream its your code. Your code is doing something that iostream isn't expecting it to do and so iostream fails. It sounds like you may be trying to directly access a function or a variable in iostream that is private instead of using the correct function to return the value you need look over your code at what functions/variables your using from iostream are you using those correctly if so then it may be that you forgot the "using namespace std;" after your includes


Weird Error in C++ Program Please Help.?

Hey Guys I keep getting this error:


Error 1 error C2109: subscript requires array or pointer type





it is the only error my program is showing here is my code:





// In a header file


//grades.h





#ifndef GRADES_H


#define GRADES_H





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





struct Grades


{


string names;


int scores;


};





#endif

Weird Error in C++ Program Please Help.?
The problem is scores and names are not defined as


array. You are trying to access it as an arrary.


Remove [count]. That should solve this problem.





cout %26lt;%26lt; "Name:";


cin %26gt;%26gt; Grade.names;





cout %26lt;%26lt; "Test Score:";


cin %26gt;%26gt; Grade.scores;
Reply:not a C++ developer, but i believe it has something to do with your array, for instance in Grades you have string names and int scores





an example of what causes Error C2109





// C2109.cpp


int main() {


int a, b[10] = {0};


a[0] = 1; // C2109 ------ ERROR


b[0] = 1; // OK


}
Reply:not sure but instead of this :





Grade.scores[count];





wouldn't this be more appropriate





Grade[count].scores;


Can someone help me write this in C language?

Write a function that will take in a FILE pointer and a double array as parameters, and return an integer. The pointer is to a text file that you will read data from, and the file data (which represents a set of scores) will be read into the array. Have the function read the value into the array, and return the number of items read.

Can someone help me write this in C language?
int func(FILE *fp, int **a) {


/* Fill it up */





return value;


}
Reply:CC c c c c cccc C c c c c C c c cccc c C C C.com


Help with C Program?

Please help me create a program that does this.





Create a story that will have certain words (nouns, verbs, etc.) filled in by the user. You'll need to use gets() and the strcpy() functions to accomplish this. Be sure that your prompts are complete by asking for the type of word you're looking for and the tense (if necessary). Keep all words that are the same part of speech in an array of pointer. Values need not be randomized. Try to make a story that will be funny! J You should have at least ten words filled in by the user.

Help with C Program?
WTF?


http://answers.yahoo.com/question/index;...


Why have you double posted? to get more answers? don't do it it annoys people especially me I have already answered your other question.


I believe this also comes under cheating in community guidelines


"creating multiple accounts or posting content for the sole purpose of gaining points or soliciting others for points is not permitted."

blazing star

Grpahics in c?

is their is any graphics function that will tell us the postiton of the pointer at that time i now about getx() but it is giving only 0 in all the condition

Grpahics in c?
set the path of graphics library(:\tc\bgi) in editor . You can get correct values.


Guidance on C++ question?

I've been sick for the last 2 weeks so I'm not fully caught up in my class. I only have 5 hours to do this assignment as thats all the time they give us so I have until mid-night. I'm not asking anyone to "do" this, im just asking for help but code examples would help me understand how to do this.





Write a function that adds the elements of two 3-D arrays of size [n] [2] [2]. Create and initialize a 3-D array with n=2 where all of the elements are initialized to 2. Test the function by using it to add the array to itself. Next create a 3-D array with n= 3 where all of the elements are initialized to 3. Again test the function by using it to add the array to itself.





2: Write a function to print out the elements of arrays of size [n] [2] [2]. Use the function to print the results from the above two additions.





3: Write another function to add the elements of 3-D arrays of size [n] [2] [2], except use pointer arithmetic inside the function to implement the addition. Test the function.

Guidance on C++ question?
an array is a contiguous section of memory used to store data, and it can be accessed only by index.





to declare a 3-d array, do so like this:





int array[2][2][2];





and the first element in that array is then array[0][0][0]





you can think of a 3d array like a cube - having a width, height, and depth.





so you'll need three nested for loops to iterate through your 3d arrays, like





void iterate(int n, int[][][] array) {


int i1, i2, i3 = 0;





for(i1 = 0; i1 %26lt; n; i1++) {


for(i2=0;i2%26lt; n; i2++) {


for(i3=0;i3%26lt; n; i3++) {


printf("this is the element: %d\n", array[i1][i2][i3]);


}


}


}





hope this helps a little!


}


In c programming what do this statement mean:- int * ?

i know if we use " int *p " that means it is a pointer.


but what int * means. and when do we use this.

In c programming what do this statement mean:- int * ?
here * denotes that it is not a normal variable like any other variables it holds an address of a int variable





pointers can be used in case if ur program uses printers.........


and dynamic programs also use pointers............


pointers are so usefull





may be ur new to programming


if u have any doubts aske me online


My yahoo ID is rgunday@yahoo.com
Reply:most programing languages have a structure to how to code stuff.


in c programming and many others you specify variables by first given then a type say 'int' then the variable name say 'p' then you assign it a value if you want. in this case ('int *') will indicate that the variable will be an integer pointer. But if you just leave 'int*' by itself withouth giving it a variable name. it won't compile and you get a compiler error.


ALL C programmers I need your help.?

I'm decoding a file using parity checking and checksum detections. Theres a 16bit value on the end of the date grouping. I've read it into an array using fread.





fread(%26amp;checksum_value[0], 2, 1, fp);


(this stores into array checksum_value, 2 bytes of info, 1 btye long from where the file pointer is pointing.)





My question is this, how do I get this to be an integer value. I've tried to use atoi, and strtol, with no luck... ANY ideas would be great.





Thanks in advance,

ALL C programmers I need your help.?
If checksum_value is of type unsigned char, you can convert it by shifting and ORing:





/* watch out for endianness */


int value = (checksum_value[1] %26lt;%26lt; 8) | (checksum_value[0]);





Alternatively, you could declare a 16-bit short int and read in the data w/o having to convert it manually:





short int value;


fread(%26amp;value, sizeof(value), 1, fp);

imperial

Visual C++ prog experts help!!!?

I created an application (for fun) and one of my objectives there is to make a mouse pointer disappear if mouse is not move for a specific period of time. I managed to create this one successfully just using WinAPI but I don't know how to convert it to MFC





Assuming that you are starting to create a simple window application with no user interventions or whatsoever...


1.) Where will I place the setTimer?


2.) In WinAPI, I placed all necessary codes like setTimer and the GetCursorPos() in WinMain and compared mouse current position and mouse old position inside LRESULT CALLBACK WndProc(...) function. How will I interpret it in MFC???





Please help....

Visual C++ prog experts help!!!?
If this is a dialog based application you can create the timer in the OnInitDialog method. In the timer method you can use the GetCursorPos method just as you did previously.


Visual C++ programmers... Please help...?

I am using MFC in making a simple window. My main objective is to make mouse pointer disappear when it reaches 4 seconds. I solved it myself using the Win32 API but in MFC, I find myself stuck in setting up the time...





I surfed the web and found out that I have to use OnStartTimer, OnStopTimer and OnTimer and also by using the SetTimer... but when I tried to call any of these three functions e.g. OnStartTime... my compiler cannot recognize all above-stated functions... I tried to re-intialized them in class, though it creates no error and ran, but all timers that were set failed to perform there duties...





I am not asking or begging you for the entire codes or write the codes to supply my needs... I just want the idea or your own approach to my problem...





I am already out of ideas and can't think of any ways to solve the problem...





Please... anyone... help... :(

Visual C++ programmers... Please help...?
SetTimer is a member of the window class, so make sure you call it from inside a CWnd-derived object such as your view class (it causes a WM_TIMER message to be sent so you need a window to receive it. In that same window override the WM_TIMER handler (i.e. OnTimer) to catch the message then call SetCursor or whatever to disable the cursor.





Another technique is to use a worker thread, this will allow you to run your own function in a custom thread without holding up the main thread and causing your program to freeze. Your worker thread should go to sleep for the 4 seconds so that it doesn't tie up the CPU doing nothing, so do something like this:





UINT MyThreadProc(LPVOID pParam)


{


Sleep(4000); // 4000ms == 4 seconds


s_pMyWindowPtr-%26gt;SetCursor(NULL); // or whatever


return 0;


}





Kick off this function by calling AfxBeginThread, you'll need to change your project settings to link in the multithreaded MFC libraries. This page has more info about creating worker threads:





*** UPDATED ***





You don't call OnTimer yourself, Windows calls it and you need to catch it by implementing the message handler and adding an entry to the message map. It's been years since I've used MFC, so I'm a bit hazy on the interface specifics, but if you open up your window and go to its properties then you'll have a list of all functions that you can overload. OnTimer will be one of them, I think you can double-click on it or something to have DevStudio automatically create the function for you and add the message map entry.





If you're still stuck then post again here and I'll dig out some code for you from my old archives.
Reply:Did you put an entry for ON_WM_TIMER() in your message map? It needs that for OnTimer to be called.





BEGIN_MESSAGE_MAP(mainWindow, CFrameWnd)


ON_WM_TIMER()


END_MESSAGE_MAP()


How to get the adderss in c++?

i have declared a pointer and have the hexadecimal address and stored in a file. Now i close the program. As the memory is not deallocated the vale in RAM still resides. now can i access that memory using memory address in file from any other program. i will be picking the value of address in character as i have saved it in a txt file. now my problem is how to assign a pointer to that memory address(i hav it in string format)..

How to get the adderss in c++?
No, when the program terminated that memory was returned to the operating system. Just because you didn't free the memory, it will still be freed when the program terminates. C/C++ programs only leak memory while they're running (on modern OS's anyway), when they terminate the OS can and does clean up.





What you've got is probably a relative address anyway--relative to the program that was running, not an absolute address in memory. Regardless, even if you had an exact address you couldn't access it from another program unless that program just happened to be assigned that location by the operating system. It would result in what's called a protection fault, I think.





Think about it. If any program could just grab any piece of memory, the system would crash all the time because there would be no way to protect one program from another, or even to protect the operating system. Older version of Windows/DOS suffered from that very problem.
Reply:A pointer is pretty much, just a long int. If you have it as a string, you can parse it with something like


void *ptr = (void*) strtol (str, 0, 16);


Or if you are really writing c++ (not just compiling with a c++ compiler), read the long directly from the stream:


long n = 0;


stream %26gt;%26gt; hex %26gt;%26gt; n;


void *ptr = static_cast%26lt;void*%26gt; n;





The problem however is that as far as I understand your question, this pointer was created and saved to the file by another program, not the one that is trying to read it. That will not work. You cannot access other process memory from your program. Moreover, the values of pointers only have any meaning in the context of the program that created it - the old good times when computers had 64K of memory are all gone.





If you must do what you describe (and you, porbably, don't - there must be a simpler, more elegant way to do what you need), you'll have to use shared memory. In normal, POSIX-compliant systems - like OS/X, Unix or Linux, you can use shmget() to create a shared memory segment, than shmat() to attach to it (it returns a pointer, that you can use as a normal regular pointer), shmdt() to detach, and shmctl() to destroy the segment, when you don't need it anymore. Then the porgram that creates the pointer would do shmget() and shmat(), put whatever data it needs into that address, and then store the segment id - what's returned by shmget(), NOT the pointer into the file. The other program, can read the segment id from the file (it's an integer), do shmat() to obtain the pointer, and use it ... Shared memory even survives the process - the first program can exit after creating its segment, and the second one (or anyone else) can still use it until somebody uses shmctl() to destroy it.





If you are on windoze, they may not have exactly these functions... Bill Gates has been known to violate a few standards in the past :-)


But there should be something equivalent (though, probably, more painful) you can do... try searching your IDE help for shared memory. Or install cygwin or mingw - they both provide standard-compliant libraries.
Reply:Even though you do not explicitly deallocate the memory in your program, the operating system will still reclaim the memory when your program closes. All modern operating systems behave this way to prevent memory leaks when the program closes.





The memory address your program saved to a text file will is a virtual memory address. Programs typically only deal in virtual memory, with the operating system handling mapping the virtual memory your program sees with the real memory in your computer.





Technically, the value *may* still be out there in main memory after your program closes because the OS only frees the memory; it doesn't wipe it clean. However, locating the value is much more complicated than saving the virtual address to a text file.





For the general question of how to assign a pointer to a memory address:





unsigned char* ptr = (unsigned char*) 0xabcdabcd;





However, be advised that dereferencing this pointer will result in undefined behavior and for the reasons stated earlier, this will not work for recovering what the other program stored in memory.


C++ problem arrays?

cant get this to compile is there any way to do this


#include %26lt;iostream.h%26gt;





int main()





{


int count[9],n,i;











// sets number of sales user will enter





cout %26lt;%26lt; "/n Please enter how many salaries you would like to enter: ";


cin %26gt;%26gt; n;


int *n_ptr = %26amp;n; /sets pointer for memeory allocation





// gets sale input from customer








double sales[n_ptr];


for (i= 0; i %26gt; n; ++i)


{


cout %26lt;%26lt; "/n/n Please enter sales totel " %26lt;%26lt; endl;


cin %26gt;%26gt; sales[i];


}





// computes salaries


n = 1;





int saleries[n_ptr];





for (i=0 ; i %26gt; n; ++i)


{


int saleries[i] = 200 + sales[i]*.09;


}











return 0;





}

C++ problem arrays?
1) You coded: for (i= 0; i %26gt; n; ++i)





Should the condition be "i %26lt; n"? (And not "i %26gt; n")





2) You coded:





a) double sales[n_ptr];


b) int saleries[n_ptr];





Why are you declaring the arrays using an integer's address? Shouldn't you first de-reference the pointer, and then instead use the value that is stored at that address?





Instead, code should read:





a) double sales[*n_ptr];


b) int saleries[*n_ptr];
Reply:In your code problem starts here:


double sales[n_ptr];





Above statment is incorrect both syntactically %26amp; logically. First n_ptr is an memory address not an integer value(u could have replaced that with n or *n_ptr). Also, when u declare a static array, u have to use a fixed size say 100 etc.(e.g. sales[100])





Here size of sales array is not known at compile time so u will have to use dynamic memory allocation.








double * sales[n] =NULL; // Pointer , initialize to nothing.





sales = new double[n]; // Allocate n ints and save ptr in sales.


for (int i=0; i%26lt;n; i++) {


sales[i] = 0; // Use as an normal array.


}


. . . // Use as a normal array


delete [] sales; // When done, free memory


slaes = NULL; // Clear to prevent using invalid memory reference.





Also, correct this statement:


for (i= 0; i %26gt; n; ++i)


It should be i%26lt;n
Reply:#include %26lt;iostream%26gt;





using namespace std;





int main()





{


int n,i;


cout %26lt;%26lt; "Please enter how many salaries you would like to enter: ";


cin %26gt;%26gt; n;


double *sales = new double[n];


for (i=0; i%26lt;n; i++) {


cout %26lt;%26lt; "Please enter sales total: ";


cin %26gt;%26gt; sales[i];


}


// computes salaries


int *salaries = new int[n];





for (i=0; i%26lt;n; i++) {


salaries[i] = (int) (200. + sales[i] * .09);


}





// display


for (i=0; i%26lt;n; i++) {


cout %26lt;%26lt; "sale" %26lt;%26lt; i %26lt;%26lt; "=" %26lt;%26lt; sales[i] %26lt;%26lt; ", ";


cout %26lt;%26lt; "salary" %26lt;%26lt; i %26lt;%26lt; "=" %26lt;%26lt; salaries[i] %26lt;%26lt; endl;


}





delete[] sales;


delete[] salaries;





return 0;


}

elephant ear

Can someone look over my C++ function?

Hey guys just want to bounce my algorithm of someone else to see if what I am thinking is correct.





I have a binary tree and I want to swap the sub trees of the tree. So my root node is called "root". The root node is made up of basically a variable to hold the data and a left pointer "llink" that points to the left subtree and a right pointer "rlink" that points to the right subtree.





Ok so my function is here:





template%26lt;class elemType%26gt;


void binaryTreeType%26lt;elemType%26gt;::swapSubTrees


{


nodeType Temp;


Temp = new nodeType;





Temp = root-%26gt;llink;


root-%26gt;llink = root-%26gt;rlink;





root-%26gt;rlink = Temp;


delete Temp;


}





Does this function look like it will accomplish what I want it to do?? The reason I dont test it out myself is because I have to write all the other functions for the tree but I just wanted to make sure that this works first,





Thanks!

Can someone look over my C++ function?
well, the best way to test it is to write a small test function which just uses this function, and afterwards you check the result. this is called a unittest, and it's a great concept, because you can run this test whenever you changed the code, and always can be sure that this function still works.





anyway, it's not ok. first of all, root-%26gt;llink or root-%26gt;rlink can be NULL, and then you should swap a NULL pointer, and not an allocated object.





also, nodeType must be a pointer, otherwise you can't allocate it with new.





also, you delete Temp (in the last line of the function), which means that root-%26gt;rlink is deleted, because root-%26gt;rlink points to Temp.





also, i just saw that you're actually allocating new objects, but that's not necessary.





the correct code would be this (assuming that nodeType is a pointer):





nodeType Temp=root-%26gt;llink;


root-%26gt;llink=root-%26gt;rlink;


root-%26gt;rlink=Temp;





that should be enough. or just use std::swap (in %26lt;algorithm%26gt;), which basically does the same.
Reply:yes it will work


C++ question ?

What is the scope of an object off the heap ? Can I return an object pointer to main or will it go out of scope?





Like this





myclass* function()


{


myclass* p=new myclass;


return p;


}

C++ question ?
You can remember it this way: an object that has been created using new (which would, as you wrote, be stored on the heap), has to be disposed of explicitly using delete. All that goes out of scope in your code, is the variable p but it only points to the object, and the address it points to is copied to the variable that is used in the calling function to store the return value in.





So returning a pointer to a new-ly created object is perfectly acceptable. Just don't forget to delete it in the calling function (in your case, apparently, main()).
Reply:Awe man, I have no clue what you just said, but it sounded "programmery"





I'll have to read that PDF





I have no clue but I'll star


Craps Game Source Code in C++?

My problem is I really suck at getting started. We have to use a pointer for the Player class and we have to input/output each player's (up to 10) name, balance, and how much they gained by playing the game (i.e their original balance + total winnings) from/into a txt file. I already know the rules of the game and all that because we did a simpler version of it already, I just dont get how to set up all the classes and how to change the Player class into a pointer type. HELP if you can!

Craps Game Source Code in C++?
I'm not trying to say that you want me to do your project, It's extremely difficult to explain the full scope and implications of the program in a textbox online. A markerboard would help ALOT.





So, you don't have to put it into a pointer, and pointer holds an ADDRESS. So, declare an array of pointers.





then use new to create your "players".





class player


{


//information to make the class


};





int main


{


player* players[10];


int i = 0;


while(i%26lt;9)


{


player[i] = new player;


i++;


}


}





--------------------------------------...


my point here is that you make a pointer totally separate from the player. you make a new player in memory and the pointer says where it is.


Can anyone write following in c language?

Write a function named allocAndInit() that will receive the following parameters: An int containing the number of doubles to create dynamically, and a double that contains the initial value that every item in the new memory will be initialized to. The function returns a pointer to the newly created data. It may not be a void pointer.

Can anyone write following in c language?
double * allocAndInit(int n, double value) {


double *value = (double*)malloc(n*sizeof(double);


return value;


}

lady palm

C++ programming question (1 question)?

ok i have everything done except this question...


looking at book...


no examples..


heres the qauestions...


code wins the best answer...


explain it to me too








Rewrite the following in pointer notation. Use the simplest form, assuming that this call is not part of a loop; in other words, do not include a counter which would reach the zero element:


array[0] -

C++ programming question (1 question)?
overload the - operator


array is already a pointer type


It can be *array-
Reply:ok there rally isn't enough information to answer your question (rewrite the following what?)


but heres some example code to that uses pointers to access an array element.





#define somenumber 10;


int array[ somenumber];





int * ptr =array; // now ptr is pointing at array[0];


int i = 0; // element of array


int x =*( ptr+i); // value of x equals the value of the array[i] for any i


C++ Function Implementation Data Type Question?

I have a class named Book_Inventory that has a class called BookRecord *searchByStockNumber(long stockNum). BookRecord is another class in another function that has various public and private variables.





How would I implement that function? What would that functions return type be? If it is BookRecord as the return type, should it return a pointer or not?





I can post the source somewhere else if it would help.





Any suggestions are welcome! Thank you!

C++ Function Implementation Data Type Question?
searchByStockNumber() returns a pointer to a BookRecord object. There are a couple of important things to think about when implementing this function.





First, you might be tempted to allocate a static BookRecord object in searchByStockNumber() and return a pointer to it each time. The problem with that is that if there are two callers, the first might stash the pointer away to refer to later, then after the second call, the data the first caller has a pointer to will be changed.





Second, if you allocate a new BookRecord in searchByStockNumber() and return that pointer, then somebody else is responsible for freeing it. You need to be careful not to just lose track of that pointer. Consider the following function:





foo(N)


{


BookRecord * pBook = searchByStockNumber(N);


// do more stuff...


}





In the example above, pBook goes out of scope when you exit from foo() so the memory allocated by searchByStockNumber() is lost.





I would consider writing searchByStockNumber() this way:





BOOL searchByStockNumber(long stockNum, BookRecord * pBook)


{


// do your look up here. Put the results in pBook.


// return TRUE if you found a book; FALSE if you did not.


}





(I don't remember if "BOOL" is the type name for a boolean in C++... I work in a cross-platform system that defines a type called "Boolean" that is what I use.)





This way, the caller is responsible for the pointer. The caller could do one of two things (or more, these are the obvious ones):





BookRecord * pBR = new BookRecord;


if (searchByStockNumber(number, pBR))


...


delete pBR;





or





BookRecord BR;


if (searchByStockNumber(number, %26amp;BR))


...





The suggestion to use an STL map is probably a bad one. You could have memory issues depending on the size of your inventory, and searching based on various attributes would be complex and error prone. I'm sure you're using some kind of database, which makes way more sense.





Hope this helps.
Reply:I would use an STL map. The reason is that each stockNum should be unique.





I would change your design. You need a class that represents the books (is that BookRecord?). It has methods for stockNumber, title, etc. Book_Inventory has a member attribute that is the map.





Search yahoo! or Google for C++ STL map to find the implementation.


C++ Programers...HELP?

If anyone can tell me what all this means i will be thankful for a lifetime. i SO do not want to read a 400 page book over it...:





#include %26lt;windows.h%26gt;





/* Declare Windows procedure */


LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);





/* Make the class name into a global variable */


char szClassName[ ] = "WindowsApp";





int WINAPI WinMain (HINSTANCE hThisInstance,


HINSTANCE hPrevInstance,


LPSTR lpszArgument,


int nFunsterStil)





{


HWND hwnd; /* This is the handle for our window */


MSG messages; /* Here messages to the application are saved */


WNDCLASSEX wincl; /* Data structure for the windowclass */





/* The Window structure */


wincl.hInstance = hThisInstance;


wincl.lpszClassName = szClassName;


wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */


wincl.style = CS_DBLCLKS; /* Catch double-clicks */


wincl.cbSize = sizeof (WNDCLASSEX);





/* Use default icon and mouse-pointer */


wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);


wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);


wincl.hCursor = LoadCursor (NULL, IDC_ARROW);


wincl.lpszMenuName = NULL; /* No menu */


wincl.cbClsExtra = 0; /* No extra bytes after the window class */


wincl.cbWndExtra = 0; /* structure or the window instance */


/* Use Windows's default color as the background of the window */


wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;





/* Register the window class, and if it fails quit the program */


if (!RegisterClassEx (%26amp;wincl))


return 0;





/* The class is registered, let's create the program*/


hwnd = CreateWindowEx (


0, /* Extended possibilites for variation */


szClassName, /* Classname */


"First Program", /* Title Text */


WS_OVERLAPPEDWINDOW, /* default window */


CW_USEDEFAULT, /* Windows decides the position */


CW_USEDEFAULT, /* where the window ends up on the screen */


200, /* The programs width */


150, /* and height in pixels */


HWND_DESKTOP, /* The window is a child-window to desktop */


NULL, /* No menu */


hThisInstance, /* Program Instance handler */


NULL /* No Window Creation data */


);





/* Make the window visible on the screen */


ShowWindow (hwnd, nFunsterStil);





/* Run the message loop. It will run until GetMessage() returns 0 */


while (GetMessage (%26amp;messages, NULL, 0, 0))


{


/* Translate virtual-key messages into character messages */


TranslateMessage(%26amp;messages);


/* Send message to WindowProcedure */


DispatchMessage(%26amp;messages);


}





/* The program return-value is 0 - The value that PostQuitMessage() gave */


return messages.wParam;


}








/* This function is called by the Windows function DispatchMessage() */





LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)


{


switch (message) /* handle the messages */


{


case WM_DESTROY:


PostQuitMessage (0); /* send a WM_QUIT to the message queue */


break;


default: /* for messages that we don't deal with */


return DefWindowProc (hwnd, message, wParam, lParam);


}





return 0;


}

C++ Programers...HELP?
Sounds like a bloody excruciating way to open a windows dialogue box with an exit button.


Saturday, May 22, 2010

C++ returning enumeration from function?

How do i go about returning an enumeration from a function?





via global pointer?





i.e





int myFunction()


{


if(x=1)


{


enum value {val1 = 1, val2 = 2}


}


else


{


enum value {val1 = 2, val2 = 3}


}


}





How would I go about passing the enum back to the main function? Thanks!

C++ returning enumeration from function?
enum is not a type by itself, it's a type category. A variable can't be of type enum, it could only be of a specific enum type.





So, your syntax is not valid.


Here is an example:





enum TypeColor


{ RED, BLUE, GREEN, OTHER};





TypeColor GetColor(char* in_colorName)


{


TypeColor VarColor = OTHER;


if (stricmp(in_colorName, "red" == 0))


VarColor = RED


else if (stricmp(in_colorName, "blue" == 0))


VarColor = BLUE


else if (stricmp(in_colorName, "green" == 0))


VarColor = GREEN;


return VarColor;


}





int main()


{


TypeColor myColor = GetColor("green");


}
Reply:Check this out... maybe it will help.





http://www.thescripts.com/forum/thread68...
Reply:When you declare an enumeration, it's like you are declaring a new data type. The caller of the function must have access to the declaration, and the funciton itself needs access to it. In your example, you'd probably declare it globally, before any code needs to use it. Don't declare the enum inside a function.





Here's a rewrite of your code.





//First, declare and define the enum:





enum value {val1 = 1, val2 = 2};





value myFunction(int x) //function returns type 'value'


{


value retval;





if (x == 1) //DOUBLE equals here!!


{


retval = val1;


}


else if (x == 2)


{


retval = val2;


}





//TODO: decide what you want to do if it's neither!!





return retval;


}





The calling code would look like this:





value val = MyFunction(1);

snow of june

C++ questions?

Here is my assignment, and the design I have to use. I've already made the classes.





Design for Program 3 Client Code


1) Declare grad student pointer and allocate temporary grad student


2) Initialize student counter


3) Open the input file


4) Use end of file loop to read in students from file (use temporary dynamic student)


a. count the number of students in the file


5) Deallocate the temporary graduate student


6) Close input file


7) Allocate a dynamic array of grad students of the proper size


8) Re-open input file


9) Use end of file loop to read in students from file


a. read each one into the dynamic student array


10) Close input file


11) Traverse the dynamic student array, print each one's data to the screen


12) Open the input file FOR WRITING using an ofstream


13) Traverse the dynamic student array, print each one's data to the file


14) Close the output file stream


15) Deallocate the dynamic student array





How do I traverse the input file using the temp dynamic student?

C++ questions?
what VS are you running? Managed or non-Managed?





if 6 use printf to show the data to screen, but then make a temp FILE and load the dynamic array into it then print the temp file.


C++ for beginners?

what is a pointer


why can it be useful, disadvantage or disadvantage.


how is it similar to the goto command that is not recommended in language

C++ for beginners?
A pointer is a variable, it's similar to an integer in that it is a 32 bit number. But the value of this number is the location of a memory cell where a piece of data begins. That data can be anything, another pointer, an integer, a character string, or a data structure.





They are advantageous because if you are passing large structures to a function, you can pass the pointer instead and avoid the large memory copy onto the stack. Also, if you need to modify the contents of the memory, you can pass the pointer to a function and modify away.





Some of the disadvantages are that typically when allocating pointers you use the new or malloc functions which require you to call delete or free on that piece of memory when you are done using it. Failure to do so creates memory leaks. Using a non-allocated pointer can also lead to confusing bugs where you think a piece of memory is valid but it isn't.





It is not the least bit similar to the goto command. Goto is not recommended because with all the available loop choices, only a beginner programmer wouldn't know how to write loops w/o using goto.
Reply:A pointer is a way to store lists of data in memory by pointing to the next memory address the program should go to find the next required data.





Pointer %26gt; data1 Pointer %26gt; data 2 Pointer%26gt; data3... etc...





It's better then an array because it uses less memory and processing power.





You can even take it farther when you start to make link lists using pointers...








The goto command refers to the line number or subroutine name the program should hop too for the next insturctions(some languages use line numbers and others use a subroutine like name).





It's similar because like the goto command is pointing to where the next instructions should be and the pointer is pointing to where the next memory address can be found.





I hope this helps if not send me a line at


admin@chaoticpulse.com





edit* just in case your curious a pointer knows to stop when it finds a nil at the last memory address.
Reply:lol.... Why dont you just look it up in your textbook,instead of asking us... We wouldn't be there during your programming test either.LOL
Reply:Hi. A pointer is like any other variable, except it holds a memory address. Pointers are the core for c programming. They are extremely useful for communication, and sharing data with control. For example, with pointers, you can get multiple return values, in a manner of speaking. A function is only allowed to return one value. But what if you want more then that? Pointers and references are the answers.





bool AllocInt(int * ptr)


{


ptr = 0;


ptr = new int;





if (!ptr)


return false;


else


return true;


}





The above function can now be used to allocate some memory from the heap to hold an int. But that function will also let you know if the allocation was succesful, or of it failed.





int * Num;





if(AllocInt(Num))


{


std::cout%26lt;%26lt; "Allocation successful!";


}else


std::cout%26lt;%26lt;"No more memory available!";





Without pointers, you would have to check if the allocation was succesful yourself:





int * AllocInt(void)


{


return new int;


}





int * ptr = 0;


ptr = AllocInt();





if (ptr)


{


std::cout%26lt;%26lt;"Allocation successful";


}else





std::cout%26lt;%26lt;No more memory available!";
Reply:In C++ pointers are special variables which store the address( where the variable is located in the memory) of other variables .