C++, return array from function [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Im building this subnet calculator but now im stuck, with array. I want to create new int function that will return array, but I don't know how I tried many things but still don't have idea, think it will have to do something with pointers. I want to create new function starting at "while(octet4>0)". so octet4 gets passed into function and function should return fully functional array which I can use then in main. Hope somebody will know answer for what im looking for, hope solution would not be too complicated because Im just learning programming and thought this would be fun project to take on.
int main() {
int i=0,j,q,s,size=8,temp;
int binary_ip[8];
int netmask;
int mask;
int octet1, octet2, octet3, octet4;
string ip;
cout<<"Vnesite IP naslov, npr. 192.168.32.55:"<<endl;
cin>>ip;
cout<<"Vnesite netmasko, npr. /27:"<<endl;
cin>>netmask;
stringstream stream(ip);
char ch;
stream >> octet1 >> ch >> octet2 >> ch >> octet3 >> ch >> octet4;
while(octet4>0){
binary_ip[i]=octet4%2;
i++;
octet4=octet4/2;
}
switch(i){
case 7:binary_ip[7]=0;
break;
case 6:for(s=6;s<=7;s++)binary_ip[s]=0;
break;
case 5:for(s=5;s<=7;s++)binary_ip[s]=0;
break;
case 4:for(s=4;s<=7;s++)binary_ip[s]=0;
break;
case 3:for(s=3;s<=7;s++)binary_ip[s]=0;
break;
case 2:for(s=2;s<=7;s++)binary_ip[s]=0;
break;
case 1:for(s=1;s<=7;s++)binary_ip[s]=0;
break;
}
for(q=0;q<size/2;q++){
temp=binary_ip[size-1-q];
binary_ip[size-1-q]=binary_ip[q];
binary_ip[q]=temp;}
return 0;
}

Some options:
Use std::array instead of a regular C array. Those are easier to work with and you are already using standard library. http://www.learncpp.com/cpp-tutorial/6-15-an-introduction-to-stdarray/
Have your function fill-in the array, rather than create and return it:
void MakeArray(int octet4, int binary_ip[8]) ;
Use pointers, allocate array with "new" and free it with "delete". You'll need a way to know the size of the array, however.

#include <iostream>
int array(int octet4, int binary_ip[]);
int main()
{
int binary_ip[6];
int octet4 = 55;
int i = 0;
i = array(octet4, binary_ip);//binary_ip passes in the address of the first element in the array
}
int array(int octet4, int binary_ip[])
{
int i = 0;
while(octet4>0)
{
binary_ip[i]=octet4%2;
i++;
octet4=octet4/2;
}
return i;
}
or you can use a vector like Daniel H suggested
void array(int octet4, std::vector<int> &binary_ip)
{
while(octet4>0)
{
binary_ip.push_back(octet4%2);
octet4=octet4/2;
}
}
int main()
{
std::vector<int> binary_ip;
int octet4 = 55;
array(octet4, binary_ip);
}

Related

Why won't the string push or pop in stack [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
This is an assignment given to me.
I am a noob just started programming.
The string as a whole won't push onto the stack and how to pop it.
Problem statement:- divide a whole string consisting of a full name, divide the string into 3 parts to get the first name middle name and surname and display them in the order of surname first name middle name USING STACKS ONLY.
I've tried using 2D stack
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string>
using namespace std;
using std :: string;
char s1[100];
char s2[50],s3[50],s4[50];
int i=0,j=0,k=0,max1=9,top=-1;
char stack[10][10];
char re[10];
void push(char val[])
{
if(top>=max1)
{
cout<<"Stack overflow";
}
else
{
top++;
int a=0;
for (int i=0;i<stack[top]['\0'];i++)
{
stack[top][a]=val[i];
a++;
}
}
}
char* pop()
{
if(top<0)
{
cout<<"Stack underflow";
}
else
{
//for(int j=0;j<=top)
for(int i=0;i<stack[top]['\0'];i++)
{
re[i]=stack[top][i];
top--;
return re;
}
}
}
void divstring()
{
for(i=0;s1[i]!=' ';i++)
{
s2[i]=s1[i];
}
s2[i]='\0';
i++;
while(s1[i]!=' ')
{
s3[j]=s1[i];
j++;
i++;
}
s3[j]='\0';
i++;
while(s1[i]!='\0')
{
s4[k]=s1[i];
k++;
i++;
}
s4[k]='\0';
i++;
}
int main()
{
//clrscr();
cout<<"Enter the string: ";
gets(s1);
divstring();
cout<<"The 1 part is "<<s2<<endl;
cout<<"The 2 part is "<<s3<<endl;
cout<<"The 3 part is "<<s4<<endl;
// getch();
push(s1);
push(s2);
push(s3);
cout<<pop();
return 1;
}
There are no compile time errors but the strings don't get pushed onto the stack nor popped.
There's multiple problems here.
There is no such thing as a 2D stack. A stack is one dimensional. It's got one usable end. In C++, you use std::stack, push(), pop() and empty().
You need to get rid of the global variables.
You seem to want to implement your own stack. You need to decide, do you want to implement a stack, that is one question. Or, do you want to use an existing stack to perform the assignment? that's a different question. I can't tell between the two.
You should use std::string.
You don't handle boundary condition. For example passing a string without spaces will loop infinitely in
for(i=0;s1[i]!=' ';i++)
The push function is very confused, here's a working version
void push(char val[])
{
if (top >= max1)
{
cout << "Stack overflow";
}
else
{
top++;
int i = 0;
for (; val[i] != '\0'; i++)
stack[top][i] = val[i];
stack[top][i] = '\0';
}
}
There are many ways you could improve this, you could use the C strcpy function instead of copying your strings by hand. Or, heaven forbid, you could use some C++, like std::string and std::stack.

What are the advantages of late binding? Give one example in context of function pointers in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Firstly, let me clarify this question doesn't explain my doubt clearly. To set the context clear. I'm asking this question specifically with regard to function pointers in C/C++.
I know the difference between early binding and late binding and how it works. What I would like to understand is the following with one example using function pointers in C/C++:
In many textbooks, it has been mentioned :
advantage of late binding is that it is more flexible than early
binding, because decisions about what function to call do not need to
be made until run time.
Also, it mentions:
With late binding, the program has to read the address held in the
pointer and then jump to that address. This involves one extra step,
making it slightly slower.
#include <iostream>
using namespace std;
int Add(int nX, int nY)
{
return nX + nY;
}
int Subtract(int nX, int nY)
{
return nX - nY;
}
int Multiply(int nX, int nY)
{
return nX * nY;
}
int main()
{
int nX;
cout << "Enter a number: ";
cin >> nX;
int nY;
cout << "Enter another number: ";
cin >> nY;
int nOperation;
do
{
cout << "Enter an operation (0=add, 1=subtract, 2=multiply): ";
cin >> nOperation;
} while (nOperation < 0 || nOperation > 2);
// Create a function pointer named pFcn (yes, the syntax is ugly)
int (*pFcn)(int, int);
// Set pFcn to point to the function the user chose
switch (nOperation)
{
case 0: pFcn = Add; break;
case 1: pFcn = Subtract; break;
case 2: pFcn = Multiply; break;
}
// Call the function that pFcn is pointing to with nX and nY as parameters
cout << "The answer is: " << pFcn(nX, nY) << endl;
return 0;
}
here, there is no advantage of using late binding and early binding as in the example below should be preferred.
int nResult = 0;
switch (nOperation)
{
case 0: nResult = Add(nX, nY); break;
case 1: nResult = Subtract(nX, nY); break;
case 2: nResult = Multiply(nX, nY); break;
}
cout << "The answer is: " << nResult << endl;
Could someone explain with an easy example like below where late binding is advantageous and why should someone choose it over early binding?
OK, I'm going to skip over the whole "early binding vs late binding" definition question and pretend you asked "why would someone use function pointers instead of a switch statement?"
Because function pointers are more flexible. They aren't static. Let's take the business end of your code:
int InvokeOperation(int nOperation, int nX, int nY)
{
switch (nOperation)
{
case 0: return Add(nX, nY);
case 1: return Subtract(nX, nY);
case 2: return Multiply(nX, nY);
}
}
That's nice and functional. But it's not flexible. Why? Because all of the functions that can be called are defined by InvokeOperation; if you want to add a new operation, you have to be able to change InvokeOperation.
By contrast, if you used function pointers, you can build a whole registry of operations:
using Func = int(*)(int, int);
struct Op{Func func; std::string name;};
std::vector<Func> funcs =
{
{&Add, "Add"},
{&Subtract, "Subtract"},
{&Multiply, "Multiply"},
};
int InvokeOperation(int nOperation, int nX, int nY)
{
return funcs[nOperation].func(nX, nY);
}
Now, if you want to add more operations, just insert elements into funcs. If InvokeOperation were part of some library, you wouldn't necessarily have the right to change it. With static binding, you would have an inflexible system; what it supports is what it will always support.
With dynamic binding, you can add whatever stuff you want, whether you have the right to modify the library directly or not.

Runtime erro with exit code 6 on online judge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am doing my c++ homework on an online judge. There are m strings with a length of n. I need to find the minimal expression of a new string, and then insert it in an trie tree. For each string, I need to return the "positon number" of the first identical string.
Following is my code:
#include <cstdio>
using namespace std;
struct trie_node
{
trie_node * firstSon;
trie_node * nextBro;
char value;
bool isKey;
int firstPos;
trie_node(char value):firstSon(NULL), nextBro(NULL), value(value), isKey(false), firstPos(-1){}
};
class trie_Tree
{
public:
trie_Tree();
int searchStr(char* desStr, int len, int selfPos);
private:
trie_node* searchChar(trie_node* fatherNode, char desChar);
trie_node* root;
};
trie_Tree::trie_Tree()
{
root = new trie_node('0');
}
int trie_Tree::searchStr(char * desStr, int len, int selfPos)
{
trie_node* fatherNode = root;
for (int i=0; i<len; i++)
{
fatherNode = searchChar(fatherNode, desStr[i]);
}
if (!fatherNode->isKey)
{
fatherNode->isKey=true;
fatherNode->firstPos=selfPos;
}
return fatherNode->firstPos;
}
trie_node* trie_Tree::searchChar(trie_node* fatherNode, char desChar)
{
if (fatherNode->firstSon==NULL)
{
fatherNode->firstSon = new trie_node(desChar);
return fatherNode->firstSon;
}
trie_node* travNode = fatherNode->firstSon;
while (travNode->nextBro!=NULL)
{
if (travNode->value==desChar) return travNode;
travNode=travNode->nextBro;
}
if (travNode->value==desChar) return travNode;
else
{
travNode->nextBro = new trie_node(desChar);
return travNode->nextBro;
}
}
char* getMinPre(char *s, int _size)
{
int min=0, trav=1;
while (trav<_size && min<_size)
{
int i;
for (i=0; i<_size; i++)
{
if (s[(min+i)%_size]<s[(trav+i)%_size])
{
trav=trav+i+1;
break;
}
else if (s[(min+i)%_size]>s[(trav+i)%_size])
{
min=trav;
trav=trav+1;
break;
}
}
if (i==_size) break;
}
char * result=new char[_size];
for (int i=0; i<_size; i++)
{
result[i]=s[(min+i)%_size];
}
return result;
}
int main()
{
int m, n, result=0;
scanf("%d %d", &m, &n);
trie_Tree tt=trie_Tree();
char* s=new char[n+1];
for (int i=0; i<m; i++)
{
scanf("%s", s);
s=getMinPre(s, n);
result = tt.searchStr(s, n, i);
printf("%d\n", result);
}
delete[] s;
return 0;
}
I compiled my code with VS and g++, and runned my program lots of times for testing. It worked perfectly.
But when the online judge system returned runtime error(exitcode 6).
I googled "exit code 6". It is raised by the program itself, e.g. by making the abort() system call. It can be caused by new and delete operation. But I still cannot debug my code.
Anyone can help me?
That's a lot of code, but some things to look into:
Inside your main function you allocate s: char* s=new char[n+1];.
You pass s into char* getMinPre(char *s, int _size).
getMinPre allocates another buffer, and returns it, overwriting s: s=getMinPre(s, n); (memory leak of initial s buffer).
This potentially happens a lot in the main function's loop, hence you may run out of memory. (getMinPre allocating and overwriting the pointer to allocated buffer).
Since this is an online judge platform, I'd recommend coming up with extreme test cases (min, max elements, tons of iterations) and running them locally.
Also: add some debug information. You can even encapsulate them within #ifdef so you won't have to remove them.
In your trie_Tree constructor, you use new to allocate dynamic memory, but I don't find you delete that object anywhere. Similarly, in searchChar, you allocate a lot of son nodes but never delete them. Also in getMinPre. All of them will lead to memory leak. The only memory you freed is the result in main().
In C++, dynamic memory management is a really complex topic and error prone, every time you allocate some memory with new, you need to keep in mind deallocate them with delete somewhere. Like in C, every time you use malloc(), you need free().
There are a lot of libraries you can use instead of managing the memory yourself. For a linked list, you may consider std::vector in header<vector>.
BTW, I think this code looks like C with Class, not C++.

probmem with comparing string c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I just came from C to C++ and find difficulties with compare string method.
I have a simple task. I need to create a class of school Teachers, then make an object array, and after withdrow all Teachers, who's subject is similar to testSubject.
So here is my class
class Teacher
{
private:
string FamilyName;
string Name;
string Patronymic;
string sex;
int exp;
std::string subject;
string speciality;
int age;
public:
Teacher();
int getExp();
string getSubject();
int getAge();
void show();
};
And here is my func, that withdrow the list of Teachers, teaching the input subject
void ListTeacherSub (Teacher spis[], int n)
{
//List of teachers, who's subject is like testSubject
std::string testSubject;
cout<<"Enter test subject "; cin>>testSubject;
for (int i=0; i<n; i++)
{
if (spis[n].getSubject().compare(testSubject) == 0)
spis[i].show();
}
}
Here it is main() function
int main()
{
Teacher *spis;
int n;
cout<<"Enter numbers of student "; cin>>n;
spis = new Teacher[n];
for (int i=0; i<n; i++)
{
spis[i].show();
}
ListTeacherAge(spis, n);
ListTeacherEx(spis, n);
ListTeacherSub(spis, n);
delete[] spis;
return 0;
}
So, everything is working nice, but when program reaches ListTeacherSub(spis, n) it is stops working. I used to work with strcmp only, but it doesn't works with string, as I understood.
So I decided to look for different realizations, and found that one http://www.cplusplus.com/reference/string/string/compare/
How can i fix my problem?
This
if (spis[n].getSubject().compare(testSubject) == 0)
should be
if (spis[i].getSubject().compare(testSubject) == 0)
This is incorrect (and causes undefined behaviour as it going beyond the end of the array):
if (spis[n].getSubject().compare(testSubject) == 0)
as it using n and not the loop counter i.
Other:
always check the result of input operations to ensure variables have been correctly populated and subsequent code is not using uninitialised or stale values:
if (std::cin >> n)
{
spis = new Teacher[n];
}
prefer to avoid explicit dynamic memory management. In this case std::vector<Teacher> would be suitable:
if (std::cin >> n)
{
std::vector<Teacher> spis(n);
for (Teacher& t) t.show();
}
Pass spis by const Teacher& to functions to avoid copy (and the parameter n is now superfluous).
std::string instances can be compared using ==.

Calling a function pointer causes an error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to build a dynamic array of objects using pointers arithmetic. However, the compiler return the following error in this line in the main.cpp
(*(lista+n))(id1,seleccion1,edad1,camiseta1);
error: no match for call to '(jugador) (int &, int & short, short int &, short int &)'
any suggestion is welcome, thanks.
This is the class.
class jugador
{
private:
int id;
short seleccion;
short edad;
short camiseta;
public:
jugador();
jugador(int ID, short SELECCION, short EDAD, short CAMISETA);
int obtener_id();
short obtener_seleccion();
short obtener_edad();
short obtener_camiseta();
void cambiar_id(int nueva_id);
void cambiar_seleccion(short nueva_seleccion);
void cambiar_edad(short nueva_edad);
void cambiar_camiseta(short nueva_edad);
void cambiar_todo(int nueva_ID, short nueva_SELECCION, short nueva_EDAD, short nueva_CAMISETA);
void mostrar_jugador();
};
The constructors...
jugador::jugador()
{
id=999999;
seleccion=32;
edad=99;
camiseta=99;
}
jugador::jugador(int ID, short SELECCION, short EDAD, short CAMISETA)
{
id=ID;
seleccion=SELECCION;
edad=EDAD;
camiseta=CAMISETA;
}
Here is the full code.
Is there a special reason you are not using std::vector<jugador> Check this thread for the advantages of replacing realloc with vector
You have not given enough information so here is what I can tell from the looks of the error:
(*(lista+n))(id1,seleccion1,edad1,camiseta1);
that is NOT a function pointer, it's not even pointing to a function in the first place.
It seems like you are trying to construct an array of jugador by moving the lista pointer. If that is what you want to do then you can do late initialization.
jugador * lista; //< unitialized pointer
int n = 11; //< your number of players, lets suppose 11
lista = new jugador[11]; // now you have an array of jugadores
for(int i = 0; i != n; ++i)
{
lista[i] = jugador(id1,seleccion1,edad1,camiseta1);
}
// use your jugadores, let's suppose you want to use the tenth jugador
jugador *iterator = lista;
iterator+10;
use(*iterator); //*iterator variable holds your 10th jugador object
delete[] lista;
You are using realloc in your code, I suggest you try new and delete instead. Or else provide an explanation of why using realloc is a good choice.
Another thing I noticed in your code is that you don't free the memory you are using. Thus you have a memory leak.
If you need more jugador the use std::copy to achieve that
// let's say in this point you need 20 jugador more
jugador * newlista = new jugador[n+20];
std::copy(lista, lista+11, newlista);
delete[] lista; //you delete the old buffer
for(int i = 11; i != n+20; ++i)
{
newlista[i] = jugador(id1,seleccion1,edad1,camiseta1);
}
// and now newlista has your jugadores, you can even make a function that does that
delete[] newlista ; // delete your jugadores
I am completely agreed with Claudiordgz's response. However, if you want to call the constructor with parameters (without making extra copies) you will need to make an array of pointers instead of an array of objects. I am pasting a version of your code with that. However, I still think that a version using vectors is safer and superior.
Code:
int main()
{
int id1;
short seleccion1, edad1, camiseta1;
jugador arreglo[5];
int n = 0, i;
char opcion = 's';
jugador **lista=NULL;
while (opcion == 's')
{
lista = new jugador*[n];
cout<<"id: "<<endl;
cin>>id1;
cout<<"Seleccion: "<<endl;
cin>>seleccion1;
cout<<"Edad: "<<endl;
cin>>edad1;
cout<<"Camiseta: "<<endl;
cin>>camiseta1;
lista[n] = new jugador(id1,seleccion1,edad1,camiseta1);
n++;
cout << "Desea ingresar otro elemento? (s/n): ";
cin >> opcion;
}
cout << "\nArreglo completo\n";
for (i=0; i<n; i++)
{
lista[n].mostrar_jugador();
}
//deallocating memory
for (int i=0; i<n; i++)
{
delete jugador[i];
}
delete [] jugador;
return 0;
}