tag:blogger.com,1999:blog-26474103274276619142024-03-04T20:04:02.255-08:00learning C++...Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.comBlogger10125tag:blogger.com,1999:blog-2647410327427661914.post-24482222687635020402010-04-19T07:14:00.000-07:002010-04-19T07:21:54.986-07:00new operator in C++Allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object. <br />[::] new [placement] new-type-name [new-initializer]<br />[::] new [placement] ( type-name ) [new-initializer]<br />If unsuccessful, new returns zero or throws an exception. <br />When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.<br />Use the delete operator to deallocate the memory allocated with the new operator.<br /><br />The following example allocates and then frees a two-dimensional array of characters of size dim by 10. When allocating a multidimensional array, all dimensions except the first must be constant expressions that evaluate to positive values; the leftmost array dimension can be any expression that evaluates to a positive value. When allocating an array using the new operator, the first dimension can be zero — the new operator returns a unique pointer.<br />char (*pchar)[10] = new char[dim][10];<br />delete [] pchar;<br /><br />The type-name cannot contain const, volatile, class declarations, or enumeration declarations. The new operator does not allocate reference types. The new operator cannot be used to allocate a function, but it can be used to allocate pointers to functions.Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-68455754538898589592010-04-19T06:54:00.000-07:002010-04-19T07:11:39.052-07:00Dynamic memory allocationLast month, I presented in a job interview. One question posted to me about the dynamic memory allocation, I have totally no idea. The question is if you don't use "malloc", what-else can help you get the address, below was the differences about functions in dynamic memory allocation.<table><br /><tr><br /><td>Function</td><br /><td>Task</td><br /></tr><br /><tr><br /><td>malloc</td><br /><td>Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space</td><br /></tr><br /><tr><br /><td>calloc</td><br /><td>Allocates space for an array of elements initializes them to zero and returns a pointer to the memory</td><br /></tr><br /><tr><br /><td>free</td><br /><td>Frees previously allocated space</td><br /></tr><br /><tr><br /><td>realloc</td><br /><td>Modifies the size of previously allocated space.</td><br /></tr><br /></table><br /><span style="font-weight:bold;">Memory allocations process:<br /></span><br />According to the conceptual view the program instructions and global and static variable in a permanent storage area and local area variables are stored in stacks. The memory space that is located between these two regions in available for dynamic allocation during the execution of the program. The free memory region is called the heap. The size of heap keeps changing when program is executed due to creation and death of variables that are local for functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations, the memory allocation functions mentioned above will return a null pointer.<br /><br /><span style="font-weight:bold;">Allocating a block of memory:<br /></span><br />A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:<br /><br />ptr=(cast-type*)malloc(byte-size);<br /><br />ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.<br /><br />Example:<br /><br />x=(int*)malloc(100*sizeof(int));<br /><br />On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int<br /><br /><span style="font-weight:bold;">Allocating multiple blocks of memory:<br /></span><br />Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:<br /><br />ptr=(cast-type*) calloc(n,elem-size);<br /><br />The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned. <br /><br /><span style="font-weight:bold;">Releasing the used space:</span><br /><br />Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.<br /><br />free(ptr);<br /><br />ptr is a pointer that has been created by using malloc or calloc.<br /><br /><span style="font-weight:bold;">To alter the size of allocated memory:<br /></span><br />The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : <br /><br />ptr=realloc(ptr,newsize);Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-50242664577549312022010-03-13T08:48:00.000-08:002010-03-13T09:12:25.700-08:00My solution for QueueHere is my solution for Queue which we are asked to be finished by Fardad in this week class.
<br /><pre>
<br />//queue.h
<br />class Queue;
<br />class Node{
<br /> int data;
<br /> Node* next;
<br /> Node(int data , Node* next = (Node*)0);
<br /> friend class Queue;
<br />};
<br />
<br />class Queue{
<br /> Node* head;
<br /> Node* tail;
<br />public:
<br /> Queue(); // empty list
<br /> void add(int data); // adds to tail of the list
<br /> int remove(); // removes from head
<br /> bool IsEmpty();// true if empty
<br /> ~Queue();
<br />};
<br />
<br />//queue.cpp
<br />#include "queue.h"
<br />Node::Node(int data , Node* next){
<br /> this->data = data;
<br /> this->next = next;
<br />}
<br />Queue::Queue(){
<br /> head = (Node*)0;
<br /> tail = (Node*)0;
<br />}
<br />void Queue::add(int data){
<br /> if (head==tail && !head){
<br /> Node* temp = new Node(data, tail);
<br /> head = temp;
<br /> tail = temp;
<br /> }
<br /> else{
<br /> Node* temp = new Node(data, tail->next);
<br /> tail->next = temp;
<br /> tail = temp;
<br /> }
<br />}
<br />int Queue::remove(){
<br /> int data = head->data;
<br /> Node* ToDel = head;
<br /> head = head->next;
<br /> delete ToDel;
<br /> return data;
<br />}
<br />bool Queue::IsEmpty(){
<br /> return !head;
<br />}
<br />Queue::~Queue(){
<br /> while(!IsEmpty()){
<br /> remove();
<br /> }
<br />}
<br />//queuemain.cpp
<br />#include <iostream>
<br />using namespace std;
<br />#include "queue.h"
<br />
<br />int main(){
<br /> Queue Q;
<br /> int i;
<br /> for(i=10;i<=50;i+=10){
<br /> cout<<"Add into a queue "<<i<<endl;
<br /> Q.add(i);
<br /> }
<br /> while(!Q.IsEmpty()){
<br /> cout<<Q.remove()<<endl;
<br /> }
<br /> return 0;
<br />}
<br /></pre>output as:
<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVEUj2MBzBi9RYqB93hX4HzP9ulSEj86iYJRgwf1gepG2zFR1eC_Frcp8lCNqzdjUuz5iZub-X6p1taH1xqRb05wWoGXm4vWVP1RJQx5vJNgDLCk1r_-UXNiY-w7LMWFENRqvak7I2ZT5P/s1600-h/queue.jpg"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 206px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVEUj2MBzBi9RYqB93hX4HzP9ulSEj86iYJRgwf1gepG2zFR1eC_Frcp8lCNqzdjUuz5iZub-X6p1taH1xqRb05wWoGXm4vWVP1RJQx5vJNgDLCk1r_-UXNiY-w7LMWFENRqvak7I2ZT5P/s320/queue.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5448166804397813346" /></a>
<br />Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-2268883649342156622010-03-13T06:53:00.000-08:002010-03-13T07:55:14.275-08:00Some concepts in C and C++Those questions are found when I prepared for my job interview question.They might be simple questions but I've never think of them.Hope that I can understand better, and also for anyone are learning C and C++.<br /><br /><span style="font-weight:bold;">Why the constructor can't be virtual?</span> <br />A: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error. The reason is a constructor can not be virtual because at the time when the constructor is invoked the virtual table (vtable) would not be available in the memory.<br />Virtual allows us to call a function knowing only the interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the what you want to create exactly. Hence call to a constructor can't be virtual.<br /><br /><span style="font-weight:bold;">Difference between delete and destructor in c++? </span><br />Delete can deallocate the memory of those objects which are created by using the new operator whereas the destructor can delete any object once the life of the object ends.(this is normally when a program ends)<br /><br /><span style="font-weight:bold;">Differences between Structure and Class.</span><br />1.Structure cannot be inherited. <br />2.Structure is a value data type whereas Class is a reference type.<br />3.All declarations inside a structure are by default public whereas by default all the members inside the class are private.<br />4.Structure instances cannot be used as operand to arithmetic operators like +-*/ . But object (instances of classes) can be (using operator overloading). <br />5.A structure can't declare protected members,a class can. <br />6.We can't inherit a structue from another structure, which we can do in class.<br /><br /><span style="font-weight:bold;">Difference between "overloading" and "overriding"?</span><br />Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.<br /><br />There are many valuable comments on it.Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-20538221370597962292010-02-18T09:46:00.000-08:002010-02-18T10:25:25.035-08:00Challenges solution : MyPrint()Here is my solution for MyPrint(). <br /><pre><br />#include <stdio.h><br />#include <conio.h><br />#include <stdarg.h><br />void print_int_hex(int val,int alg)<br />{<br /> int i;<br /> if (val==0)<br /> {<br /> _putch('0');<br /> }<br /> else<br /> {<br /> if (val/alg)<br /> {<br /> i = val % alg;<br /> print_int_hex(val/alg,alg);<br /> }<br /> else<br /> i = val % alg;<br /> if (i>9)<br /> {<br /> i=i-10+'a';<br /> _putch(i);<br /> }<br /> else<br /> _putch(i?i+48:48);<br /> }<br />}<br /><br />void print_float(double val)<br />{<br /> int temp = val *100;<br /><br /> if (val==0)<br /> {<br /> _putch('0');<br /> }<br /> else<br /> {<br /> print_int_hex(temp/100,10);<br /> _putch('.');<br /> print_int_hex(temp%100,10); <br /> }<br />}<br /><br />void MyPrint(char* pString,...)<br />{<br /> int i=0;<br /> int ch;<br /> const char* str;<br /> double f;<br /> <br /> va_list args;<br /> va_start(args, pString);<br /> while (pString[i])<br /> {<br /> if (pString[i]=='%')<br /> {<br /> i++;<br /> switch(pString[i])<br /> {<br /> case 'c':<br /> ch = va_arg(args, int);<br /> _putch(ch);<br /> break;<br /> case 's':<br /> str = va_arg(args, const char*);<br /> _cputs(str);<br /> break;<br /> case 'd':<br /> ch = va_arg(args,int);<br /> if (ch<0)<br /> {<br /> _putch('-');<br /> ch=ch*(-1);<br /> }<br /> print_int_hex(ch,10);<br /> break;<br /> case 'x':<br /> case 'X':<br /> ch = va_arg(args, int);<br /> print_int_hex(ch,16);<br /> break;<br /> case 'f':<br /> f = va_arg(args, double);<br /> print_float(f);<br /> break;<br /> }<br /> i++;<br /> }<br /> _putch(pString[i]);<br /> i++; <br /> }<br /> va_end(args);<br />}<br /><br />int main()<br />{<br /> MyPrint("int %d, char %c, string %s, hex %x, float %f", -102, 'A', "hello", 31, 12.34567);<br /> return 0;<br />} <br /></pre><br />Result as: <br />int -102, char A, string hello, hex 1f, float 12.34<br />For float, I thought might be have better solution.Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com1tag:blogger.com,1999:blog-2647410327427661914.post-23039191635814818342010-02-03T07:59:00.000-08:002010-02-03T08:30:11.443-08:00Optimizing bio_display()Here is the source code:<pre>void bio_display(const char *str, int row, int col, int len){<br /> bio_move(row, col);<br /> if(len <= 0){<br /> bio_putstr(str);<br /> }<br /> else{<br /> int i;<br /> for(i=0; i< len && str[i];i++){<br /> bio_putch(str[i]);<br /> }<br /> for(;i< len;i++){<br /> bio_putch(' ');<br /> }<br /> }<br />}</pre>To optimize it, I got this solution :<br /><pre>void bio_display(const char *str, int row, int col, int len) {<br /> bio_move(row, col);<br /> if( len <= 0)<br /> bio_putstr(str);<br /> else {<br /> for(;len>0; len--) bio_putch(*str ? *str++ : ' ' );<br /> }<br />}</pre>From the same logic, it also can be shortened as:<br /><pre>void bio_display(const char *str, int row, int col, int len) {<br /> for((bio_move(row, col), (len <= 0)?bio_putstr(str):0); len>0; len--)<br /> bio_putch(*str ? *str++ : ' ' );<br />} </pre>I tried to use bio_putstr() instead of bio_putch() which Farad mentioned in the class, but considered the length of the string I insisted to use bio_putch().Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-52033174021366158872010-01-28T20:38:00.000-08:002010-01-28T21:09:39.372-08:00week 3 challenge - bio_putint(int val)My result as below, has been test.<br />void sep(int val)<br />{<br /> int i;<br /> if (val/10)<br /> {<br /> i = val % 10;<br /> sep(val/10);<br /> }<br /> else <br /> i = val % 10;<br /> _putch(i?i+48:48);<br />}<br />void bio_putint(int val)<br />{<br /> sep(val);<br />}Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-71014075320505313432010-01-27T21:02:00.000-08:002010-01-27T21:26:46.954-08:00First IRC meetingIn our first IRC meeting, Fardad introduced some guidelines to us to get familiar with IRC environment and its culture. Through the meeting, we impressed the knowledge we learned from the classes. Meanwhile, we learnt lots new knowledge. There are two interested website as: <br /><a href="http://www.pastebin.ca">http://www.pastebin.ca</a> is a website to copy the text and post it, then copy the url and pass the url share with your friend.<br /><a href="http://tinyurl.com">http://tinyurl.com</a> is a website to help you make a long url short to tiny one. When you clicked the short one, it will redirect to the long one.<br /><br />Starting from IRC is very good for us to get start to familiar with developing environments. For open source programming, by WIKI or IRC is very common for people communicating with their teammates. <br /><br />But be honest, IRC meetings and chats are very slow. Especially when talking with an 8 people’s group, some people did not pay attention that will cause the meeting last much longer. And Fardad need to talk to all the groups that will take him longer time. <br />Is there better way to solve this problem?Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0tag:blogger.com,1999:blog-2647410327427661914.post-21091824922937460122010-01-25T19:39:00.000-08:002010-01-25T20:48:53.131-08:00The declaration and algorithm about Pointers<span style="font-weight:bold;">I.Declare a pointer</span><br /><p>int* p; p is an integer pointer variable <br />int* p[n]; p is a pointer array by the amount of n-pointer pointing to an integer elements<br />int* p(); p points to a function which return an integer pointer <br />int (*p)(); p is a function pointer, points to a function which return an integer value<br />int** p; p is an pointer variable points to another pointer, this pointer point to an integer </p><span style="font-weight:bold;">II. Algorithm</span><br />(1)get address: <p>use "&" get the address of the variable </p>(2)get value: <p>use "*" get the target of the pointer</p>(3)assign operate: <p>·assign variable address to an pointer<br /> int i; <br /> int* p = &i;<br />·between the same type pointer variable assignment <br /> int* p = &i;<br /> int * q = p;<br />·address of the first element in the array assign to pointer <br /> int a[3]={10,20,30}; <br /> int* p = a;<br />·assigned to the function entry address of a pointer variable<br /> typedef int (*funcptr)();<br /> funcptr p;<br /> extern int foo();<br /> p = &foo; </p>(4)Addition and Subtract<p>·array pointer<br /> int a[5]={10,20,30,40,50}; <br /> int* p = a;<br /> p+=3; p-=3; p++; P--;<br />·subtract a pointer from a pointer of the same type,<br /> get the difference in the subscripts of the two elements. So, the resulting type isn't a pointer but is a signed integer type.</p>(5)Comparison<p>·The two pointers point to the same array of variables can be greater than, less than, equal to the comparison operator.<br />·Compared with Zero,p==0 means point to NULL。 </p>Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com1tag:blogger.com,1999:blog-2647410327427661914.post-50963531565449448242010-01-11T18:27:00.000-08:002010-01-11T18:49:35.913-08:00Create an IRC account and loginCreate an IRC account and login<br /><br />1. google search "ChatZilla", download and install it.<br />2. From "FireFox"=>"Tools" => select "ChatZilla".<br />3. commands:<br /> <span style="font-weight: bold;"></span><span style="font-weight: bold;"></span><span style="font-weight: bold;"></span><span>/server irc.freenode.net /* connect to server */<br /> /join #seneca" /* join #Seneca channel */<br /> /nick nickname /* Change your nickname */<br /> /leave /* leave the channel */<br /> /query nickname /* open a private chat with some one */<br /><br />Enjoy!<br /><br /></span><span style="font-weight: bold;"></span>Gwenhttp://www.blogger.com/profile/03665928819206884165noreply@blogger.com0