How modify character arrays inside functions? - c++

I want to update a character array by reversing it. The character array is correct when output inside function, but not in main after the function is called.
I believe that the character array is passed by reference, but when updating the array, the character array in the main function is not updated. What am I doing wrong here?
#include <iostream>
#include <cstring>
using namespace std;
void StringReverse(char *ch, int size){
char sh[100] = {0};
for(int i=0 ; i<size ; i++){
sh[i] = ch[size-1-i];
}
sh[size] = '\0';
ch = sh;
cout<<ch<<endl;
}
int main(){
char ch[100];
cin.getline(ch, 100);
int size = strlen(ch);
StringReverse(ch,size);
cout<<ch;
}
I do not want to print the result inside the function, but update the character array 'ch' in the main function by calling the function StringReverse.

You want to use strncpy() instead of ch = sh;. As other people have kindly pointed, you are not modifying ch. You are modifying the local variable sh only.
#include <iostream>
#include <cstring>
using namespace std;
void StringReverse(char *ch, int size){
char sh[100] = {0};
for(int i=0 ; i<size ; i++){
sh[i] = ch[size-1-i];
}
sh[size] = '\0';
strncpy(ch, sh, 100);
cout<<ch<<endl;
}
int main(){
char ch[100];
cin.getline(ch, 100);
int size = strlen(ch);
StringReverse(ch,size);
cout<<ch;
}

The ch in StringReverse function is local to that function. And that's why when assign ch = sh;, it doesn't change the ch in main.
While you can copy sh, a better approach is to use reverse in-place so that you wouldn't need a local copy at all.
For example:
void StringReverse(char *ch, int size){
for(int i = 0, j= size - 1 ; i < j ; i++, j--){
int t = ch[i];
ch[i] = ch[j];
ch[j] = t;
}
cout << ch << endl;
}
If you use std::string instead of a plain char array, it would be a lot easier to do this. You could for example use std::reverse.

Related

Reversing characters from input

I am trying to reverse a char which has been provided in input from an user. I am having issues with the reverse function, particularly the loop. I can't get it to work- can I get advice?
#include <iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char temp[len];
for(int i=len; i>len; --i) {
temp[i]+=input[i];
}
return temp;
}
int main()
{
char input[100];
while(cin>>input) {
cout << reverse(input);
}
return 0;
}
Your Program has few issues
You're trying to return local variable address i.e. temp array address. The Function will return the address to main function. Since memory might get cleaned so it will print garbage value present at the address.
As Rohan Bari mentioned variable length array might cause undefined behavior. There for you can create a constant length array i.e.
char temp[100];
or you can dynamically allocate array on heap. Memory allocated on heap do not get cleared after termination of block but we have to manually delete it.
char* temp = new char[len];
As array start from 0 it goes till len-1 so loop condition should start from len-1 and has to go till 0 to reverse.
+ operator do not work's with array or char even if you are trying to add just char it preforms normal integer addition of their ASCII value.
Here is improved version of your code
#include<iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char* temp = new char [len]; // or you can use char temp[100];
int j = 0; //temp variable to enter values from 0th index if we use same as loop it just enter in the same order as original char array.
for(int i=len-1; i>=0; --i) {
temp[j++] = input[i];
}
temp[j] = '\0';
return temp;
}
You have got several errors in the program.
The variable-length arrays are used here:
char temp[len];
This should not be applied in C++ since this invokes undefined-behavior. Note that this is a valid statement in the C99 standard.
There is a better alternative to this. That is to take the std::string built-in type in use.
In the following line:
temp[i] += input[i];
You are not sequentially adding one character after another, but the values of them in a single integer. This could be not a problem if temp was of the type std::string.
The reverse function should look like this:
const char *reverse(char *input) {
int len = strlen(input);
std::string temp;
while (len--)
temp += input[len];
return temp.c_str();
}
len should actually be (len-1) and i should be >= 0 not len, so from (len-1) to 0 your loop should run.
for(int i = len-1; i >= 0; i--){}
You have to allocate the new array with the new keyword if you don't want to use a string. The following code does what you need:
char* reverse(char* input)
{
int len = strlen(input);
char* temp = new char[len + 1];
for (int i = len; i >= 0; --i)
{
temp[len-i-1] = input[i];
}
temp[len] = '\0';
return temp;
}
You could use a std::stack to reverse your input:
std::stack<char> s;
char c;
while (std::cin >> c)
{
s.push(c);
}
while (!s.empty())
{
std::cout << s.top();
s.pop();
}
It's 2021. Use the STL. If your instructor isn't aware of it or doesn't allow you to use it, your instructor is not keeping up-to-date and you should fire your instructor.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string input{};
while(std::getline(std::cin, input)) {
std::reverse(std::begin(input), std::end(input));
std::cout << input << '\n';
}
return 0;
}
There's quite many things wrong with the code as many people have already mentioned! Since you want to implement this without using STL it can be done this way,
#include <iostream>
using namespace std;
#include <cstring>
void reverse(char* input,int len) { //added len as argument
char temp[len];
for(int i=len-1; i>=0; --i) {
temp[len-i-1]=input[i];
cout<<temp[len-i-1]; //printing while reversing
}
cout<<endl;
}
int main()
{
char input[100];
int len=0;
//using do while since it has to run atleast once
do{
cin.getline(input,100);
len=strlen(input);
input[len]='\0';
if(len!=0)
reverse(input,len);
}while(len!=0) ;
return 0;
}

Reversing string using stack (static array) in c++

i am new to this concept in c++
i am trying to reverse string using stack static array implementation in c++.
Input: qwerty
expected output: ytrewq
output which i am getting is: trewq
Can some one explain me why is this happening and any possible solution.
Here's my code
#include <iostream>
#include <string>
using namespace std;
#define SIZE 10
string arr[SIZE];
unsigned a = -1;
void push(char ch) {
a = a + 1;
arr[a] = ch;
}
void pop() {
a = a - 1;
}
void display() {
for (int j = a; j >= 0; j--)
cout << arr[j];
}
int main() {
string str;
getline(cin, str);
for (int i = 0; i < (str.length() - 1); i++)
push(str[i]);
display();
}
Remove the "-1" in :
for(int i=0;i<(str.length())-1;i++)
Else your array doesn't contains the last character.
I made the test without the -1, it works well.
The condition "< str.length()" is enough to loop on all string caracter.
In similar case, use the debugger to see what contains your variable. In these case the variable "arr" don't contains the last input caracter.
You push everything on the stack, so the last element can be popped first. Then do popping to fill a reversed strng. The stack should be a char array.
As this is typically a task, the rest is your puzzle.
Pop typically gives you the top element as:
char pop() {
char ch = arr[a];
--a;
return ch;
}
The correct way to reverse a string would be to do:
std::reverse(str.begin(), str.end());
But I think this might be homework/study so look at your output. You are just missing the last letter. That suggests the upper limit of your loop is wrong doesn't it?

c++ assigning the index of char array outside a class

Trying to figure out why my char array inside a class or struct does not accept all characters as it normally would do when not inside a class or struct.
#include <iostream>
using namespace std;
const int SIZE = 10;
struct A{
char address[SIZE];
}
int main(){
char address_from_main[SIZE];
A a;
address_from_main[2] = 9;
cout<<"address from main: "<<address_from_main[2]<<endl;
a.address[2] = 9;
a.address[3] = 'a';
cout<<"show 2: "<<a.address[2]<<" , but didnt show"<<endl;
cout<<"show 3: "<<a.address[3]<<" , this one did"<<endl;
output = address from main: 9\nshow 2: , but didnt show \nshow3: , this one did
How is this possible?
Does anybody have any idea how to fix this?
Many thanks.
In your first example, as you said, that is working fine but that is impossible as the array you are declaring is a char array and you are storing a numeric value as int value in it.
address[2] = 9;//assigning a int value not a character
cout<<address[2]<<endl;// hence will not print 9 but some junk value
address[2] = '9';//Correct, assigning a numeric character
cout<<address[2]<<endl;// Will print 9
Also read about memory allocation for a integer and a character and see what is the difference between byte allocation for both.
Guess having an unsigned char did the trick. Eventually.
#include <iostream>
#include <fstream>
using namespace std;
struct Frame {
unsigned char total_frame[16];
int length_frame = 5;
int checksum;
bool checksum_good = 1;
bool complete = 1;
};
int main(){
Frame total;
// open a file in read mode.
ifstream infile;
infile.open("input-file.txt");
cout << "Reading from the file" << endl;
//reading from the file
for(int i=0; i<16; ++i){
cin>>total.total_frame[i];
}
cout<<"read"<<endl;
//reading out from the buffer to the screen
for(int i=0; i<16; ++i){
cout<<total.total_frame[i]<<endl;
}
return 0;
}

Reversing the sequence of a string [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 8 years ago.
Improve this question
A fairly simple program, trying to reverse the characters in a null terminated string in C++, but something seems to be going wrong.
#include <iostream>
using namespace std;
void reverse(char*);
int main(){
char *str;
cout<< "Please enter a string, no spaces please..";
cin >> str;
//reverse(str);
}
void reverse(char *str){
char temp;
size_t len = strlen(str);
for (size_t i = 0; i < len/2; i--)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
Getting the following error
Bus error: 10
Any help appreciated.
Allocate memory for str before use char *str = new char[25];
In reverse function for for loop increment i for (size_t i = 0; i < len/2; i++ )
Deallocate memory after use delete [] str ;
You are decrementing iterator i insted of incrementing it. A little bit compact version of yours:
#include <algorithm>
#include <cstring>
void reverse(char* const str)
{
unsigned long const len = strlen(str);
for(unsigned long i = 0; i < len >> 1; i++)
std::swap(str[len - i - 1], str[i]);
}
#include <algorithm>
#include <string>
#include <iostream>
#include <cstring>
int main() {
// You can't read something to nowhere.
// String will be holded in static array.
char str[1024];
// To keep it as null terminated string after
// writing of inputed string: `std::cin` don't
// write null character after writing of data.
memset(str, 0, 1024);
std::cin >> str;
// If you do reversing of strings in C++,
// you shouldn't use hand written loops:
std::reverse(str, str + strlen(str));
std::cout << str << std::endl;
}
Try this modified version of your code:
#include <iostream>
#include <cstring>
using namespace std;
void reverse(char*);
int main(){
char str[1024]; // buffer of 1024 chars
cout<< "Please enter a string, no spaces please..";
cin >> str;
reverse(str);
cout << "\nReversed: " << str;
}
void reverse(char *str){
char temp;
size_t len = strlen(str);
for (size_t i = 0; i < len/2; i++) // loop until half of the user input
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
I simply added the array of char char str[1024]; to store the user input.. and changed the loop to: for (size_t i = 0; i < len/2; i++)
However, you must be very careful with the above code.. it works properly if the size of the input is less than the array fixed size.

Calling an element of a string as a char in C++

This is for use in a GUI using C++ and FLTK.
Say I have a string x = "ABCDEFG" and an array of boxes y[7].
I'd want to put one of those letters as the label on a box using a for loop such as:
for (int i=0; i<7; i++) {
y[i] = new Fl_Box(120+31*i,40,30,30,"A");
}
but rather than "A" on all of them, of course I'd want "A" on y[0], "B" on y[1], "C" on y[2], etc - with the letter called from the string as the element x[i].
I tried simply using x[0], etc and found that it needed a conversion to char.
I then tried &x[0] and found it just prints the whole string on each of them as its a const char.
Assuming FL_Box expects a C-string style (null terminated), consider using a temporary value.
std::string(x[i], 1).c_str()
This is similar to passing
char temp[2] = { 0 };
temp[0] = x[i];
and passing temp.
you can use the substr() method of std::string like:
for (int i=0; i<7; i++) {
y[i] = new Fl_Box(120+31*i,40,30,30, x.substr(i, 1).c_str());
}
Here is the signature of substr():
string substr (size_t pos = 0, size_t len = npos) const;
Here is a quick test program an its output.
#include <stdio.h>
#include <string>
int main(int argc, char *argv[])
{
std::string x = "ABCDEFG";
for (int i = 0; i < 7; ++i) {
printf("i(%d) c(%s)\n", i, x.substr(i, 1).c_str());
}
return 0;
}
# ./a.out
i(0) c(A)
i(1) c(B)
i(2) c(C)
i(3) c(D)
i(4) c(E)
i(5) c(F)
i(6) c(G)