Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an integer array list and I want to make left right pointer array list to access this. But for more than 690.000 elements (for example 700.000) the program stops and says `Segmentation fault (core dumped). I have used std::vector before but I have to use simple array list because of speed. And This code is not about my program it is very simple way to tell my problem with code. And I have to use global variable because this code run in a class methods.
int k=698900;
int n1=k/2;
int n2=k/2;
int *left[n1];
int *right[n2];
int list[k];
for(int i=0; i<k; i++){
list[i] = i;
}
for(int i=0; i<n1; i++){
left[i] = &list[i];
}
for(int i=0; i<n2; i++){
right[i] = &list[i];
}
for(int i=0; i<n2; i++){
cout << *right[i] << endl;
}
As #PaulR already said in the comments your problem is a stack overflow. You can solve this problems a few ways. If you're categorically against changing your code then you can adjust the stack size in your compiler. How exactly that is done depends on your compiler (gcc example and VS example). You can also adjust it at run-time but that's an OS dependent function, so I'm not going to go into details about that.
The solution that I would prefer is allocate the memory on the heap. This can be done by either allocating the arrays on the heap int **left = new int*[n1]; but then you have to remember to call delete []left; when you don't need the memory anymore. The far more elegant solution would be to use a std::vector instead.
I challenge you to compile this with all optimizations on and tell me that it's significantly slower than your code.
int k=698900;
int n1=k/2;
int n2=k/2;
//not that I condone storing raw pointers in a vector
//admittedly this is a rather dangerous thing to do
//storing indices would be smarter because upon adding
//elements the memory could be relocated
std::vector<int *> left(n1);
std::vector<int *> right(n2);
std::vector<int> list(k);
for(int i=0; i<k; i++){
list[i] = i;
}
for(int i=0; i<n1; i++){
left[i] = &list[i];
}
for(int i=0; i<n2; i++){
right[i] = &list[i];
}
for(int i=0; i<n2; i++){
cout << *right[i] << endl;
}
Like #PaulR mentioned you can also allocate the arrays statically (static int *left[n1];) or globally (outside of any function or class declaration/definition)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to concatenate two arrays that were initialized from file input into one dynamic array and returning it to an output file but while testing I found out that the returned dynamic array is initialized with random numbers. I'm sorry for my lack of experience as I am a beginner.. These are my input text files
Input1.txt
1
2
3
Input2.txt
4
5
6
and this is my code ..
#include <iostream>
#include <fstream>
using namespace std;
int * concatenate(int *a1,int *a2,int size);
int main() {
int size = 3;
int arr1[size];
int arr2[size];
ifstream fin;
ofstream fout;
fin.open("input1.txt");
for(int i = 0; i < size; i++) {
int value;
fin>>arr1[i];
cout<<arr1[i]<<endl;
}
fin.close();
fin.open("input2.txt");
for(int j = 0; j < size; j++) {
fin>>arr2[j];
cout<<arr2[j]<<endl;
}
int *arr3 = concatenate(arr1,arr2,size);
cout<<arr3[1];
return 0;
}
int * concatenate(int *a1,int *a2,int size) {
int * r = new int[size*2];
for(int i = 0; i > size*2; i++) {
if(i < size)
r[i] = a1[i];
else
r[i] = a2[i-size];
}
return r;
}
If you're using c++ you should consider using vectors instead of arrays.
They make operations like these way easier.
Here's for reference:
https://en.cppreference.com/w/cpp/container/vector
https://www.geeksforgeeks.org/vector-in-cpp-stl/
You can referer to this post to see how to concatenate two vectors. Concatenating two std::vectors
If you want to stick to your method there's an error in your concatenate function.
You never actually enter the for-loop since your condition for stopping is wrong. The condition in your loop is continue iterating while i > size * 2 but, with i = 0 at the start, that will never be true thus you will never enter the loop. You can fix this just by inverting the comparaison like so i < size * 2.
To avoid this kind of errors you can try to setup a debugger and go through your code line by line seeing the values of variables and what lines are actually executed. This method will help you catch a lot of small mistakes like these.
As for the random values in your return array it's because C and C++ don't clean the memory being allocated by your program when creating a new array or calling malloc for example.
you seem to have a small typo in your code in the last for loop,
for(int i = 0; i > size*2; i++)
i think you ment (watch the comparison sign)
for (int i = 0; i < size*2; i++)
you can try to cout values from the code you think doesn't work, or even better, use an IDE like Visual studio to debug your code when it fails for no apparent reason, which allows you to see your code executing line by line in the future.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to make a 2D array where user inputs the number of elements that array can take, also the elements inside the array. I think I manage to create the array, but when I try to put some elements inside it, for example 2x2 array and putting 2 as all of its elements i get this as the output. Here is the code:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int rowCount,colCount;
cout<<"Enter the number of rows in Grid-Land:";
cin>>rowCount;
cout<<"Enter the number of columns in Grid-Land:";
cin>>colCount;
int** arr = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
arr[i] = new int[colCount];
cout<<"Enter the garbage amounts at the nodes of the MxN Grid-Land:"<<endl; //Elements of the array
for(int i=0; i<rowCount; i++){
for (int j=0; i<colCount; i++)
cin>>arr[i][j];
}
cout<<"\nThe 2-D Array is:\n";
for(int i=0;i<rowCount;i++){
for(int j=0;j<colCount;j++){
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
return 0;
}
It's a typo. Instead of using the "j" variable in the inner loop while taking the input, you have used the "i" variable.
You got a typo in the for loop in which you prompt the user for the values of the array. You switched j's for i's so you're really only iterating over one column and never prompting the user for the rest of the values.
Change this
for(int i=0; i<rowCount; i++){
for (int j=0; i<colCount; i++)
cin>>arr[i][j];
}
}
For this
for(int i=0; i<rowCount; i++){
for (int j=0; j<colCount; j++)
cin>>arr[i][j];
}
}
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 5 years ago.
Improve this question
Here is the code I have:
string words[n];
.
.
.
for(int j = 0; j < sizeof(words)/sizeof(words[0]); j++){
if(words[j].find(new_word) != std::string::npos){...} //abort(3) called
}
However, SIGABRT isn't called in the same code when I call find on a normal string, like
for(int j = 0; j < sizeof(words)/sizeof(words[0]); j++){
if(s.find(new_word) != std::string::npos){...} //abort(3) NOT called
Why is this behavior happening? Isn't words[j] referring to a string element?
Edit: adding the entire code, in case the snippet isn't sufficient :
#include <stdio.h>
#include<string>
#include<stdlib.h>
#include<iostream>
using namespace std;
int main() {
int T;
cin>>T;
while (T--){
int n;
cin>>n;
string words[n];
for(int i =0; i<n;i++){
cin>>words[i];
}
string s;
cin>>s;
string new_word;
//start inserting spaces now
for(int i =1;i<=s.length();i++){
new_word = s.substr(0,i);
//cout<<s<<endl;
//start scanning
for(int j = 0; j < sizeof(words)/sizeof(words[0]); j++){
if(words[j].find(new_word) != std::string::npos){
s = s.erase(s.find(new_word), new_word.length());
}
}
}
if(s.length() == 0)
cout<<"1"<<endl;
else
cout<<"0"<<endl ;
}
return 1;
}
Edit 2: The question is here :http://practice.geeksforgeeks.org/problems/word-break/0
It's pretty simple why it's crashing when you change that line. In the version that crashes you check whether words[j].find(new_word) is equal to std::string::npos and then call s.erase(s.find(new_word), ...). Of course, s.find(new_word) could still be std::string::npos, and string::erase throws an exception when the first argument is out of range. In the version that you say does not crash, you correctly check whether s.find(new_word) is std::string::npos before passing it to s.erase. It actually has nothing to do with whether you're using a string in an array or not.
Be it known, though, the variable length array string words[n] is not standard c++, it's a GCC extension, and so you have to look to them for documentation as to whether all strings are initialized and and whatnot. The standard C++ way to make that array would be string *words = new string[n] followed by delete[] words to free the memory. If you do that, sizeof(words) will be the size of a string pointer, not the allocated size of the array, so you would have to use n instead of sizeof(words) / sizeof(words[0]). The current best-practice would be to use a shared_ptr<string> or a unique_ptr<string> and make_shared or make_unique depending on whether or not you will have multiple aliases to the array. If you use those, you do not have to call delete (or new for that matter); the memory will be freed correctly and automatically when the *_ptr objects go out of scope.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Working on a project that reads integers from a file and puts them into a 2D array. I tested it with a 1D array but when I tried it with a 2D array I kept getting this error "invalid types ‘int[int]’ for array subscript" in my class called "Image" in this function:
void Image::read(int* arr)
{
//Nested loop that reads the file
for(int i = 0; i < height; i++)
{
for(int k = 0; k < width; k++)
{
inputFile >> arr[i][k]; //Here's where I get the error
}
}
}
And here is my main function:
int main()
{
Image test("colorado1.dat"); //File with the integers
test.setWidth(500);
test.setHeight(500);
int array[test.getHeight()][test.getWidth()];
test.read(array);
//Loop to test if the function worked
for(int i = 0; i < 500; i++)
{
for(int k = 0; k < 500; k++)
{
cout << array[i][k] << " ";
}
}
}
Take a look at this function signature:
void Image::read(int* arr);
Here, you've said that the type of arr is int*, a pointer to an integer. As a result, when you write
arr[i][k]
C++ says "hold on a second... arr is an int *, so arr[i] is an int, and you can't apply the square bracket operator to a pair of int values."
To fix this, you'll need to change up the way that you handle parameters to this function. You could either pass in an int**, which would represent a pointer to a pointer to an int, or consider using something like std::vector<std::vector<int>>, which is safer and easier to use.
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 5 years ago.
Improve this question
in my code,I defined an array:
std::vector< std::pair<int,int> > *line_sep=new std::vector< std::pair<int,int> > [16];
in my test,when i use delete []line_sep;i found my computer memory usage is rising slowly.
i just want to release line_sep memory.
16 vectors of pairs!..
exp
std::vector< std::pair<int,int> > *line_sep=new std::vector< std::pair<int,int> > [16];
for(int i=0;i<16;i++){
for(int j=0;j<1700;j++){
if(....)line_sep[i].push_back({Begin,End});
}
}
fun(line_sep);
delete []line_sep;
Yes, you would use delete[] line_sep; to free it. Anything you allocate with new[] must be freed with delete[].
However, using another std::vector would be preferred instead of using a raw pointer:
typedef std::pair<int, int> IntPair;
typedef std::vector<IntPair> IntPairVec;
std::vector<IntPairVec> line_sep(16);
for(int i = 0; i < 16; ++i)
{
for(int j = 0; j <1700; ++j)
{
if (....)
line_sep[i].push_back(std::make_pair(Begin, End));
}
}
fun(&line_sep[0]);
Or, in C++11 and later, a std::unique_ptr would also work:
using IntPair = std::pair<int,int>;
using IntPairVec = std::vector<IntPair>;
std::unique_ptr<IntPairVec[]> line_sep(new IntPairVec[16]);
for(int i = 0; i < 16; ++i)
{
for(int j = 0; j <1700; ++j)
{
if (....)
line_sep[i].push_back({Begin, End});
}
}
fun(line_sep.get());