Monday, May 24, 2010

C++ programming, editing function to return string instead of char.?

This function used to return a single letter. How can I change it so it could return a string of 6 characters?





char pop(stack *s)


{


char pop;


pop=s-%26gt;cars[s-%26gt;top];


s-%26gt;cars[s-%26gt;top]='\0';


s-%26gt;top--;





return pop;


}

C++ programming, editing function to return string instead of char.?
Hi,





The variable name pop and function name cannot be same.


I suppose you are having a structure stack. something like this:





struc stack


{


char cars[10][7];


int top;


};





Also here I am considering u are using C language and want to store 10 cars each of whose name is of at the most of 6 characters.





char* pop_operation(stack *s)


{


char *pop;


pop=(char *)malloc(sizeof(char)*7); // In C++, use


// pop =new char[7];


strcpy(pop,s-%26gt;cars[s-%26gt;top]);


s-%26gt;cars[s-%26gt;top]='\0';


s-%26gt;top--;


return pop;


}








Where ever u r calling this function, note u have to declare a string pointer before by writing,





char *str;





and at the time of call as





str=pop_operation(strucure variable or pointer as u did earlier);





U can print it as u print other strings.





In case of further more clarifications, u may query me again.





OM NAMAH SHIVAY
Reply:What you are wanting to return is a C-String, or character array. Simply declare char pop as a array of 6 characters





char pop[5];





then fill the values into the pop array, and return the value when your done with the function.


No comments:

Post a Comment