简体   繁体   中英

How'd I iterate through an array without allocating too much memory?

So, I was trying to make a program that merges two strings and then prints it, although at the end when it needs to iterate through the array it returns: exit status 101. I did some research and aparently it's because it's using too much memory. So, I was wondering if either there is a way to iterate through an array without using too much memory, or alternatively, is there another way to print all the chararcters. Here's my code:

#include <iostream>
using namespace std;
int main() {
  char NAME[]={};
  int pos = 0;
  string name1, name2; getline(cin, name1); getline(cin, name2);
  int lenght1 = name1.size()/2;
  int lenght2 = name2.size()/2;
  int pos1 = 0, pos2;
  cout << lenght1 << " " << lenght2 << endl;
  for(int i = 0; i < lenght1; i++){
    char letter = name1[pos1];
    NAME[pos] = letter;
    pos++;
    pos1++;
  }
  pos2 = pos1;
  for(int i = 0; i < lenght2; i++){
    char letter = name2[pos2];
    NAME[pos] = letter;
    pos2++;
  }
  pos = 0;
}

The issue with the code sample you posted is that you dereference the NAME array out of bounds.

Using a std::string instance for the concatenated string instead of a raw array makes implementing this simpler:

#include <iostream>
using namespace std;
int main() {
  string name1 = "";
  getline(cin, name1);
  string name2 = "";
  getline(cin, name2);
  int length1 = name1.size()/2;
  int length2 = name2.size()/2;
  cout << length1 << " " << length2 << endl;
  string concat = name1.substr(0, length1) + name2.substr(0, length2);
  cout << concat;
}

http://cpp.sh/372az

Iterating through an array does not take up any memory at all.
You are going over existing memory of the array, that is what it means to "iterate".

The problem with your code is that you are trying to assign values to memory you did not allocate, and this produces undefined, and often random behavior.

As stated in the comments, here you create array of size 0:

char NAME[]={};

So no memory is allocated.

But here you try to put a value in this array, as if it had some memory:

NAME[pos] = letter;

Where this value actually goes, depends on the condition of your computer at the time you run the program, but chances are you get some segmentation fault, or overwrite one of your other variables in some weird way.

To merge strings you need to allocate enough memory for both in the array, like so:

NAME = new char[name1.size() + name2.size + 1];

Note, the +1 is for the terminating '\0' (null character) you will need to add when working with C style strings (aka array of char ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM