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
Saturday, May 22, 2010
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.
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 .
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 .
C++ bubble sort?
Alright, i've been using bubble sort, i found some code on Cprogramming.com, but i can't figure out how to modify it to work in descending order.
Its sorting a Pointer array. (int** array = new int*[n])
IntPtr is declared as int*.
n is the size of the array...
Yahoo was being stupid and taking away my new lines, so, if it does it again, the '...' means its a new line, this is just incase
:::CODE BEGIN:::
...void sortDown(IntPtr* array, int n)
... {
... for(int x = 0; x %26lt; n; x++)
... {
... for(int y = 0; y %26lt; n - 1; y++)
... {
... if(*array[y] %26gt; *array[y+1])
... {
... IntPtr temp = array[y+1];
... array[y+1] = array[y];
... array[y] = temp;
... }
... }
... }
...}
Now i need to create a function called sortUp, same parameters as the first one, still void, but it needs to sort it in descending order
C++ bubble sort?
The order of ANY sort is determined by the comparison operation. Here, you are determining that 2 elements are out of order if the one that appears first (here array[y]) is greater than the one that appears after it (array[y+1]) and if it is, you swap. That means you are saying that having a first element greater than the second element is "wrong", which means you want lower valued elements first (descending order). The short answer is reverse your comparison (if array[y]%26lt;array[y+1).
Reply:All you have to do is reverse the %26gt; sign in the comparison to make it a %26lt; sign, then the sort will be in reverse order.
Reply:You know the usual bubble sort method. Now all you have to do is to print the array elements in reverse order like as follows
for(i=n;i%26gt;=0;i--)
{
printf(.....);//the usual stuff
}
If you don't like this, then I have another idea for you.
Create a temporary array which has the same size as this one.
Say your array name is b[].All you have to do is store the array elements in reverse order like this.
Try to use a while loop here.
{i=0;
j=n;
while(i!=n)
{
b[j]=a[i];
j--;
i--;
}
now you will be able to see the elements stored in reverse order.
Do this after the sortDown method. That way you will have all the elements sorted in descending order.
Hope this helps you. All the best.
Its sorting a Pointer array. (int** array = new int*[n])
IntPtr is declared as int*.
n is the size of the array...
Yahoo was being stupid and taking away my new lines, so, if it does it again, the '...' means its a new line, this is just incase
:::CODE BEGIN:::
...void sortDown(IntPtr* array, int n)
... {
... for(int x = 0; x %26lt; n; x++)
... {
... for(int y = 0; y %26lt; n - 1; y++)
... {
... if(*array[y] %26gt; *array[y+1])
... {
... IntPtr temp = array[y+1];
... array[y+1] = array[y];
... array[y] = temp;
... }
... }
... }
...}
Now i need to create a function called sortUp, same parameters as the first one, still void, but it needs to sort it in descending order
C++ bubble sort?
The order of ANY sort is determined by the comparison operation. Here, you are determining that 2 elements are out of order if the one that appears first (here array[y]) is greater than the one that appears after it (array[y+1]) and if it is, you swap. That means you are saying that having a first element greater than the second element is "wrong", which means you want lower valued elements first (descending order). The short answer is reverse your comparison (if array[y]%26lt;array[y+1).
Reply:All you have to do is reverse the %26gt; sign in the comparison to make it a %26lt; sign, then the sort will be in reverse order.
Reply:You know the usual bubble sort method. Now all you have to do is to print the array elements in reverse order like as follows
for(i=n;i%26gt;=0;i--)
{
printf(.....);//the usual stuff
}
If you don't like this, then I have another idea for you.
Create a temporary array which has the same size as this one.
Say your array name is b[].All you have to do is store the array elements in reverse order like this.
Try to use a while loop here.
{i=0;
j=n;
while(i!=n)
{
b[j]=a[i];
j--;
i--;
}
now you will be able to see the elements stored in reverse order.
Do this after the sortDown method. That way you will have all the elements sorted in descending order.
Hope this helps you. All the best.
Having problems understanding Malloc in C programming language !!?
#include%26lt;stdio.h%26gt;
void main()
{
char *ch;
ch= malloc(10);
}
What is the above program doing ??
ch is a character pointer. But if i am allocating 10 bytes of dynamic allocated memory what does it mean ??
why allocate 10 bytes to a character pointer ??
ps:
help:i am doing data structures.
Having problems understanding Malloc in C programming language !!?
your statement is right about the fact that you are allocating 10 bytes to a character pointer. more specifically, you are allocating 10 bytes and setting the char pointer to the first of the 10 bytes. to allocate memory for one character, what you probably should be doing is:
char *ch;
ch = (char*) malloc( sizeof(char) );
if you wanted an array of 10 characters, you would do:
char** charray = (char**) malloc( sizeof(char)*10 );
remember to free the memory once you are done with it!!!
free(ch);
free(charray);
Reply:malloc() and its derivatives are used to dynamically allocate space on the Heap for specific memory storage needs. In your example, what malloc() is doing is creating space for a character array (i.e. string) of length 10 on the Heap allowing for you to assign values of up to 10 characters into your variable 'ch'. So 'ch' could equal "dog" or "new york" etc. Don't forget to de-allocate this memory once you are done using it. C doesn't have garbage collection or anything similar!
Reply:ch now contains the address of the first character of a string of ten characters. Alternatively, ch now points to the first element of a ten-character array. malloc() allocates memory sequentially, so you could say something like this:
ch=ch+1;
and ch would then point to the second character of the string.
sweet pea
void main()
{
char *ch;
ch= malloc(10);
}
What is the above program doing ??
ch is a character pointer. But if i am allocating 10 bytes of dynamic allocated memory what does it mean ??
why allocate 10 bytes to a character pointer ??
ps:
help:i am doing data structures.
Having problems understanding Malloc in C programming language !!?
your statement is right about the fact that you are allocating 10 bytes to a character pointer. more specifically, you are allocating 10 bytes and setting the char pointer to the first of the 10 bytes. to allocate memory for one character, what you probably should be doing is:
char *ch;
ch = (char*) malloc( sizeof(char) );
if you wanted an array of 10 characters, you would do:
char** charray = (char**) malloc( sizeof(char)*10 );
remember to free the memory once you are done with it!!!
free(ch);
free(charray);
Reply:malloc() and its derivatives are used to dynamically allocate space on the Heap for specific memory storage needs. In your example, what malloc() is doing is creating space for a character array (i.e. string) of length 10 on the Heap allowing for you to assign values of up to 10 characters into your variable 'ch'. So 'ch' could equal "dog" or "new york" etc. Don't forget to de-allocate this memory once you are done using it. C doesn't have garbage collection or anything similar!
Reply:ch now contains the address of the first character of a string of ten characters. Alternatively, ch now points to the first element of a ten-character array. malloc() allocates memory sequentially, so you could say something like this:
ch=ch+1;
and ch would then point to the second character of the string.
sweet pea
Help writing in C language. i have this so far but i am lost. please help?
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.
double * allocAndInit(int n, double value)
{
double *value = (double*)malloc(n*sizeof(double);
return value;
}
Help writing in C language. i have this so far but i am lost. please help?
having value in the parameters and value as a local variable is confusing. Change that to doubleList, or something.
Then initialize a value to that first pointer.
double *d = doubleList;
then loop through double, setting
*d = value;
and then d++ will move to the next double. Make sure to only loop through n doubles.
double * allocAndInit(int n, double value)
{
double *value = (double*)malloc(n*sizeof(double);
return value;
}
Help writing in C language. i have this so far but i am lost. please help?
having value in the parameters and value as a local variable is confusing. Change that to doubleList, or something.
Then initialize a value to that first pointer.
double *d = doubleList;
then loop through double, setting
*d = value;
and then d++ will move to the next double. Make sure to only loop through n doubles.
Calling all C/C++ programmers.?
I need to store an array in a file. The array length is 1000. I want the fastest disk writing method to work. I know reading a big block from the hard disk is faster because it involves only 1 seek. I seem to have 2 optons :
Option 1) for(i=1 to 1000)
fll%26lt;%26lt;Array[i];
Option 2) Store the array contents into a single string str and then fll%26lt;%26lt;str;
where fll is the file pointer. Which would be faster. I am concerened about the performance because I need to write numericaal data in a file of size around 4 Gb.
http://cs.dal.ca/~koul/
Calling all C/C++ programmers.?
I'm a C programmer, but from the documentation I can find this looks to be true for C++ as well.
The file functions in C and C++ are buffered. This means it doesn't matter whether you write one character at a time to the file or 1000, the file won't really be written to until you fill the file buffer, flush the buffer or close the file.
Probably the best way to optimize this is to write the entire string and let C++ handle it. If the size of the array will always be the same, you could set the buffer to that size; however, it's improbable that your program will be that neat. Another option would be to be sure that the buffer is the optimal size for your hardware; i.e. if your hard drive prefers blocks of 1K, set your buffer to 1K.
Reply:Almost certainly option 2 will be faster, since you only have to do one write to disk, and so the operating system can do all sorts of optimizations. If you write them one at a time, there's not much optimization that can be done.
But, I'd try it on a small example on the real system to make sure :-)
Reply:If it is 4 gigabytes of data you had better not try to store it in an array or a string before writing it out!
Maybe that will be no problem in 2015 but in 2005, most computers do not have 4 GB of memory and even the ones that do would really be unnecessarily burdened by that approach.
Instead, why don't you just write the data out using the plain old C++ insertion operator as you describe in Option 2 - but without storing the contents in a single string beforehand?
By default, your file I/O is going to to be buffered. Let the C++ runtime library and the operating system take care of buffering.
With both approaches you mention in options 1 and 2 - they are going to be doing that anyway. No sense duplicating their work and unnecessarily staging the entire contents of a 4 GB file in memory. That 4 GB of virtual memory is going to wind up being stored on disk anyway, since your process will not have that much real memory available for it anyway. And _that_ is going to be *really* slow.
Just make sure your I/O is buffered, not unbuffered, and you should be fine. Benchmark it if you like, just to be sure. Don't be surprised though that when you try to create a 4 GB string - you have a lot of performance problems or something aborts.
bottle palm
Option 1) for(i=1 to 1000)
fll%26lt;%26lt;Array[i];
Option 2) Store the array contents into a single string str and then fll%26lt;%26lt;str;
where fll is the file pointer. Which would be faster. I am concerened about the performance because I need to write numericaal data in a file of size around 4 Gb.
http://cs.dal.ca/~koul/
Calling all C/C++ programmers.?
I'm a C programmer, but from the documentation I can find this looks to be true for C++ as well.
The file functions in C and C++ are buffered. This means it doesn't matter whether you write one character at a time to the file or 1000, the file won't really be written to until you fill the file buffer, flush the buffer or close the file.
Probably the best way to optimize this is to write the entire string and let C++ handle it. If the size of the array will always be the same, you could set the buffer to that size; however, it's improbable that your program will be that neat. Another option would be to be sure that the buffer is the optimal size for your hardware; i.e. if your hard drive prefers blocks of 1K, set your buffer to 1K.
Reply:Almost certainly option 2 will be faster, since you only have to do one write to disk, and so the operating system can do all sorts of optimizations. If you write them one at a time, there's not much optimization that can be done.
But, I'd try it on a small example on the real system to make sure :-)
Reply:If it is 4 gigabytes of data you had better not try to store it in an array or a string before writing it out!
Maybe that will be no problem in 2015 but in 2005, most computers do not have 4 GB of memory and even the ones that do would really be unnecessarily burdened by that approach.
Instead, why don't you just write the data out using the plain old C++ insertion operator as you describe in Option 2 - but without storing the contents in a single string beforehand?
By default, your file I/O is going to to be buffered. Let the C++ runtime library and the operating system take care of buffering.
With both approaches you mention in options 1 and 2 - they are going to be doing that anyway. No sense duplicating their work and unnecessarily staging the entire contents of a 4 GB file in memory. That 4 GB of virtual memory is going to wind up being stored on disk anyway, since your process will not have that much real memory available for it anyway. And _that_ is going to be *really* slow.
Just make sure your I/O is buffered, not unbuffered, and you should be fine. Benchmark it if you like, just to be sure. Don't be surprised though that when you try to create a 4 GB string - you have a lot of performance problems or something aborts.
bottle palm
Subscribe to:
Posts (Atom)