I'm having trouble getting rid of the core segmentation fault on this code. It's creating a series of names in a 3-dimensional array with the dimensions row, col, and chars, where chars stores up to 5 letters of a name.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int MAXSIZE = 11;
char*** names;
names = new char** [MAXSIZE];
cout << &names << " ";
for (int i = 0; i < MAXSIZE; ++i) {
names[i] = new char* [MAXSIZE];
cout << &names[i] << " ";
for (int j = 0; j < MAXSIZE; ++j) {
names[i][j] = new char [5];
cout << &names[i] << " " << i << j;
}
cout << endl;
}
I've inserted some debugging in there too. I see that it is able to finish assigning addresses, so I'm not sure what's going wrong. No other code is being done, even as I have deletes at the end that are all good.
Your code is ok, but remember that you can only store 4-symbol names in char[5] array.
Some modifications of your example
const int MAXSIZE = 11;
char*** func()
{
char*** names;
names = new char**[MAXSIZE];
for(int i = 0; i < MAXSIZE; ++i)
{
names[i] = new char*[MAXSIZE];
for(int j = 0; j < MAXSIZE; ++j)
{
names[i][j] = new char[5];
memset(names[i][j], 0, 5);
memcpy(names[i][j], "abcd", 4); // !!! only 4 symbols for name !!!
}
}
return names;
}
int main()
{
char ***names = func();
for(int i = 0;i < MAXSIZE;i++)
for(int j = 0;j < MAXSIZE;j++)
cout << names[i][j]<< endl;
// free memory
}
Related
The code below converts lets say array 3,9,3 to sorted array of integers 3,3,3,3,3 by converting 9 into sum of maximum possible parts.
The link to code/algorithm used in this code is answered at
https://stackoverflow.com/a/75331557/21145472
I am struck in this C++ code. When I ran it yesterday it was fine but today it gives memory leak error when function resizeArray() is run third time.
Please help fix this memory leak
#include<cmath>
#include <algorithm>
#include <iterator>
using namespace std;
void resizeArray(int *orig, int size, int newSize) {
int *resized = new int[newSize];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
int main(){
int n = 3;
int *arr = new int[n];
int arrLength = n;
arr[0] = 3;
arr[1] = 9;
arr[2] = 3;
int *arrSorted = new int[0];
int sortedArrayLength = 0;
int temp;
unsigned long long int limit = 10e4;
long long parts = 0;
int extra = 0;
int mainArrayIndex = 0;
for(int i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
for(int i = 0; i < n; i++){
parts = floor((arr[i] - 1) / (limit)) + 1;
limit = arr[i] / parts;
extra = arr[i] % parts;
for(int index = 0; index < extra; index++){
resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
arrSorted[mainArrayIndex] = limit+1;
mainArrayIndex+=1;
sortedArrayLength+=1;
}
for(int index = 0; index < parts - extra; index++){
resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
arrSorted[mainArrayIndex] = limit;
mainArrayIndex+=1;
sortedArrayLength+=1;
}
}
cout << "Array sorted steps taken" << " " << sortedArrayLength - arrLength;
cout << endl;
for(int i = 0; i < sortedArrayLength; i++){
if(i == 0)
cout << "[";
cout << arrSorted[i];
if(i < sortedArrayLength - 1)
cout << ", ";
if(i == sortedArrayLength - 1)
cout << "]";
}
delete []arr;
delete []arrSorted;
}
Your helper function's orig = resized; doesn't reassign your main function's arrSorted as you intend. Use a reference:
void resizeArray(int *&orig, ...) {
(That and the lack of including iostream are the only correctness issues I see, and this fix got rid of the error.)
I am trying to make a program where it asks the user the number of shelves and number of positions on those shelves from the user then it asks the user where he wants to enter a product.
Now I got rows and columns figured out but I can't get the full product name printed it just shows a single character of said product. Is there a way I can store an address of a string variable and store it in that column of my row to print the complete word?
This is what I have done so far.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int M = 4;
int N = 4;
char *item;
char ie[20];
// dynamically create an array of pointers of size `M`
char** A = new char*[M];
// dynamically allocate memory of size `N` for each row
for (int i = 0; i < M; i++) {
A[i] = new char[N];
}
cout << "Row num" << endl;
int row = 0;
cin >> row;
cout << "Row col" << endl;
int col = 0;
cin >> col;
//string temp;
cout << "Item" << endl;
cin >> ie;
for (int j = 0; j < strlen(ie); j++)
{
A[row][col] = ie[j];
}
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
sorry If the question is not clear or easy to understand.
First recommendation: never do like this
for (int j = 0; j < strlen(ie); j++) { /* do something */ }
Do it like this instead:
for (int i = 0; ie[i] != '\0'; ++i) { /* do something */ }
or
int ie_len = strlen(ie);
for (int j = 0; j < ie_len; ++j) { /* do something */ }
because each loop condition check it calls strlen which takes length of string to calculate this function, so it takes square of string length in first case
I recommend use std::string and std::vector to store 2D array of strings, and avoid raw pointers and especially new operator (at least for code in question body you forgot delete for this new's). If you really want mess with raw pointers, see the end of this answer, but now recommended way to do what you want (as I understand what you want):
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
int M = 4;
int N = 4;
std::vector<std::vector<std::string>> A(M);
char ie[20];
for (int i = 0; i < M; i++) {
A[i] = std::vector<std::string>(N);
}
// can be used std::fill(A.begin(), A.end(), std::vector<std::string>(N)); instead for loop above but for loop simplier to understand
cout << "Row num" << endl;
int row = 0;
cin >> row;
cout << "Row col" << endl;
int col = 0;
cin >> col;
string temp;
cout << "Item" << endl;
cin >> temp;
A[row][col] = temp;
for (int i = 0; i < M; i++)
{
cout << std::string(N * (temp.size() + 3) + 1, '-') << "\n"; // add separator to be clear what happening
cout << "| "; // add separator to be clear what happening
for (int j = 0; j < N; j++) {
A[i][j].resize(temp.size(), ' '); // for all columns has equal width to be clear what happening
cout << A[i][j] << " | ";
}
cout << endl;
}
}
example of input and output of this code:
Row num
1
Row col
2
Item
bob
-------------------------
| | | | |
-------------------------
| | | bob | |
-------------------------
| | | | |
-------------------------
| | | | |
Messing about raw pointers (your code with some editions and useful comments):
#include<iostream>
#include<cstring> // cstring not string as #PaulMcKenzie mentioned in comments for strlen
using namespace std;
int main()
{
int M = 4;
int N = 4;
char *item;
char ie[20];
// dynamically create an array of pointers of size `M`
const char*** A = new const char**[M]; // need add one more star because two for two-dimensonal array and one more for ~string~(aka char array)
// dynamically allocate memory of size `N` for each row
for (int i = 0; i < M; i++) {
A[i] = new const char*[N];
}
const char empty_string[1] = "";
for (int i = 0; i < M; ++i){
for (int j = 0; j < N; ++j){
A[i][j] = empty_string; // make empty names on all shelves
}
}
cout << "Row num" << endl;
int row = 0;
cin >> row;
cout << "Row col" << endl;
int col = 0;
cin >> col;
//string temp;
cout << "Item" << endl;
cin >> ie;
/*not need this:
for (int j = 0; j < strlen(ie); j++)
{
A[row][col] = ie[j];
}
just save adress like this:*/
A[row][col] = ie;
int ie_len = strlen(ie);
/* can be done simply:
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
but it doesn't look like table*/
// add seprators for understanding what happenning
for (int i = 0; i < M; i++)
{
// add horizontal separator
for (int j = 0; j < N * (strlen(ie) + 3) + 1; ++j){
cout << "-";
}
cout << "\n";
cout << "| "; // add separator to be clear what happening
for (int j = 0; j < N; j++) {
cout << A[i][j];
// for equal width of columns add some spaces
for (int k = strlen(A[i][j]); k < ie_len; ++k){
cout << " ";
}
cout << " | ";
}
cout << endl;
}
// not forget to delete all what u newed
for (int i = 0; i < M; i++) {
delete A[i];
}
delete A;
}
This code should determine which value in the array occurs most often, but when I try to run it, it causes an error:
#include <iostream>
using namespace std;
int f(int ptr[], int size) {
int s = 0;
int* ptr2 = new int[size];
for (int y = 0; y <= size - 1; y++) {
ptr2[y] = 0;
}
for (int o = 0; o <= size; o++) {
for (int os = 0; os < size; o++) {
if (ptr[o] == ptr[os]) ptr2[o]++;
}
}
int m;
for (int l = 0; l < size - 1; l++) {
m = ptr[0];
if (m < ptr2[l + 1]) {
s = l + 1;
}
}
return ptr[s];
};
int main() {
int size;
cout << "enter number \n";
cin >> size;
int* ptr = new int[size];
for (int l = 0; l <= size - 1; l++) {
cout << "enter number " << endl;
cin >> ptr[l];
}
cout << f(ptr, size) << endl;
delete[] ptr;
}
Your code has some bugs that need to be fixed
Do not ever use "using namespace std;"
Replace l <= size - 1 with l < size
There are more comparison problems. Fix them all
At the end of the function you have a ; Remove that.
In your function you use new, but not delete. Please delete your allocated memory.
The for loop for (int o = 0; o <= size; o++) { leads to an out of bounds desaster. Please change <= to <
In for (int os = 0; os < size; o++) { you have a typo. Please replace o++ with os++
Your software would then look like this:
#include <iostream>
int f(int ptr[], int size) {
int s = 0;
int* ptr2 = new int[size];
for (int y = 0; y < size; y++) {
ptr2[y] = 0;
}
for (int o = 0; o < size; o++) {
for (int os = 0; os < size; os++) {
if (ptr[o] == ptr[os]) ptr2[o]++;
}
}
int m;
for (int l = 0; l < size - 1; l++) {
m = ptr[0];
if (m < ptr2[l + 1]) {
s = l + 1;
}
}
delete[] ptr2;
return ptr[s];
};
int main() {
int size;
std::cout << "enter number \n";
std::cin >> size;
int* ptr = new int[size];
for (int l = 0; l < size; l++) {
std::cout << "enter number " << std::endl;
std::cin >> ptr[l];
}
std::cout << f(ptr, size) << std::endl;
delete[] ptr;
}
If you enable all compiler warnings, then you will already get some hints from clang
Additionally:
In C++ we do not use raw pointers for owned memory.
And, of course also not new and delete
Also. You should not use C-Style arrays in C++. Always use std::vector or std::array instead.
Use longer variable names
Write comments
Select an indentation style and use it consequently
By the way. With more advance C++ you could also write:
#include <iostream>
#include <utility>
#include <unordered_map>
#include <queue>
#include <vector>
#include <algorithm>
// Function to get most frequent used number in a vector
int topFrequent(std::vector<int>& numbers) {
// Count all occurences of numbers
std::unordered_map<int, size_t> counter{};
for (size_t i = 0; i < numbers.size(); i++) counter[numbers[i]]++;
// Waste some memory and sort
std::priority_queue<std::pair<int, int>> heap;
for (auto x : counter) heap.push(std::make_pair(x.second, x.first));
// Return most frequent number
return heap.top().second;
}
int main() {
// Instruct user what to do
std::cout << "How many numbers do you want to check? Please Enter a number: ";
// Get count of numbers to read
if (unsigned int count{}; (std::cin >> count) && (count > 0)) {
// Read all data
std::vector<int> data{};
std::cout << "\n\nPlease enter " << count << " values:\n";
std::copy_n(std::istream_iterator<int>(std::cin), count, std::back_inserter(data));
// Show result
std::cout << "\n\nMost frequent used number is: " << topFrequent(data) << "\n\n";
}
else std::cerr << "\n\nError: Problem with input\n\n";
}
To be compiled with C++17
I would like to point out some random integers using the regular print function, then print again the same integers using pointer notation. When I use pointer notation I run into some trouble. If anyone could send some tips it'd be much appreciated. If i comment out a specific line of code, the program will compile completely, but not with the outputs I'd like.
#include <iostream>
#include <ctime>
#include <stdlib.h> //srand(), rand()
using namespace std;
void printArray(int[], int);
//void printToday(int , );
int main()
{
int i = 0;
const int SZ = 100;
int myArray[SZ] ={0};
srand(time(0));
int myArrayTotal = 0;
int *thelight;
thelight = myArray;
for (int i = 0; i <=100; i++)
{
myArray[i]= i+rand()%1000 ;
}
cout << "Array Notation:\n\n";
printArray(myArray, SZ);
system("pause");
system("cls");
cout << "Pointer Notation: \n\n";
int k = 0;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
cout<< *(thelight + k)<< "\t";
++k; //if I comment out this line the second part of the program will run, but it isn' the values I want.
} cout<< endl;
}
}
void printArray(int ArrayName[], int ArraySize)
{
int k = 0;
for (int i = 0; i < 10; ++i)
{
for(int j = 0; j < 10 ; ++j)
{
cout << ArrayName[k] << "\t";
++k;
}cout << endl;
}
}
Thank you
I'm compiling this on linux. It will compile and run, but when I enter values for n and p, this is what my terminal looks like:
7
1.0
Segmentation fault (core dumped)
In this case, 7 is the input for n, and 1.0 is the input for p. I've tried this with different values. The idea is to use Dynamic Programming to fill in a 2D array of probabilities through recursion. Let me know if you need more info, but this is the entirety of the code.
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int n;
double p;
cin >> n;
cin >> p;
cout << n;
cout << p;
cout << "Initializing array.";
double** probability = new double*[n];
for(int i = 0; i < n; ++i)
{
probability[i] = new double[n];
}
//cout << "Beginning filling i loop.";
for(int i = 0; i < n; i++)
{
probability[i][0] = 0;
}
//cout << "Beginning filling j loop.";
for(int j = 0; j < n; j++)
{
probability[0][j] = 1;
}
//cout << "Beginning filling nested loop.";
for(int i = 1; i< n; i++)
{
for(int j = 1; j< n; j++)
{
probability[i][j] = (p * probability[i-1][j]) + ((1-p) * probability[i][j-1]);
}
}
cout << "Probability: ";
cout << probability[n][n];
//cleanup
for(int i = 0; i < n; ++i)
{
delete probability[i] ;
}
delete probability;
return 0;
}
cout << probability[n][n];
probability[][] is an n by n array. The last element is probability[n-1][n-1] , so you are running off the end of the array and invoking undefined behavior.