C :: Double Pointers And Dynamic Memory Allocation?
Nov 16, 2013
we are currently covering double pointers and memory allocation. Currently getScrabbleWords is not working. when I compile with commented code (Main() works fine) I get a segmentation fault.
This function takes an array of char* values (i.e. strings) representing all the words read from wordlist.txt. Each of these words is tested by callingcanWeMakeIt as a helper function, and pointers to the words that can be made are put into an array, myWords. Note, copies of the words are not made! In order to indicate the end of myWords, we terminate with a NULL pointer. Thus, if N words can be made from letters then myWords should have length N+1.
Suppose I wished to reallocate memory (resize) an array of pointers. Why does the following not work?(The program runs, yet yields a faulty segmentation error message. Why?):
I need to use dynamic memory allocation and use pointers to iterate through the arrays that I have already in this program. I am lost, nothing I do works and where to use the pointers. I am just looking for a push in the right direction so I can finish this project and how I can implement pointers in my program.
I'm writing a program involving a theoretical hotel. Most of the code is already written, but the part I'm having trouble with involves the very beginning of the code.
The program is designed to read in from an input file the hotel's ID number, the types of rooms it has, the Room Numbers of each room, the base rate for each room, and the rate of additional charge per person.
The code demonstrates inheritance for my Object-Oriented Programming class, as each type of room will inherit from generic class Room, but I can't seem to figure out how to make the double-pointer for dynamic allocation work.
The code is below.
Hotel.h Code: class Hotel{ int hotelID; static const int MAX_SIZE = 101; Room **rPoint;
I have declared a global variable as pointer. The program performs certain number of iterations. After every iteration, the size of memory required for the pointer changes and this pointer variable is to be accessed by different functions. Now, here is my doubt:If I allocate the memory for this global variable in a function, will the contents of the memory be lost once I exit that function. In my opinion, it should not be the case as the dynamic memory allocation takes place in "heap" and should not be affected by the call of functions.
The snippet below (or similar) compiles and runs OK but I am using Visual Studio C++ compiler. Are the lines where .nameFirst and .nameLast assigned kosher in ANSI C?
Also I am concerned about the memory allocation for these string constants. Does the runtime system put them on the heap? It doesn't seem that they are really constants since they are not defined before runtime.
I have recently bought a copy of "Jumping into C++" and have come to chapter 14 ( dynamic memory location) and have a question.
On page 153-154 an example of dynamic allocation is given for array's of int. How would the code look like for strings or structs ?
The allocation was given by:
Code: int *growArray (int* p_values, int *size) { *size *= 2; int *p_new_values = new int[ *size ]; for ( int i = 0; i < *size; ++i ) { p_new_values[ i ] = p_values[ i ]; } delete [] p_values; return p_new_values; }
Sample Code I tried to use this for an array of structs but failed completely....
I used the following struct Code:
struct user{ int days; string name; };
and the allocation function (which does not work):
Code: struct user *growarray (struct user *p_values, int *size) { *size *= 2; struct user *p_new_values = new struct user[ *size ]; for ( int i = 0; i < *size; ++i )
I am creating a connect 4 game using dynamic memory allocation the question is;
Write a two-player game of Connect Four where the user can set the width and height of the board and each player gets a turn to drop a token into the slot. Display the board using + for one side, x for the other, and _ to indicate blank spaces.
I have created the board. However I am unsure as how to make a start on getting the players to make moves.
Code: #include <iostream> using namespace std; char **create_table(int width, int height, char blank) { char **p_p_connect4 = new char*[height]; for(int i = 0; i < height; i++) { p_p_connect4[i] = new char [width];
#include <iostream> using namespace std; class Foo { public: Foo( int n );// Constructor ~Foo();// Destructor int *ptr; int N;
[Code] ....
I'm using Visual C++ 2008 version. The problem arises at the end, after the sentence 'system("pause")' is reached, which makes me think that the problem happens when calling the destructor. The destructor is called twice, the first time it's called is in the function print. The problem seems to be that the destructor can only be called once.
I know I can avoid this situation by defining the function print like this:
void print ( const Foo &f ) ...
but I would like to know if there is some way I can do this keeping the definition that I've provided.
1. Pointers can be used as pass by reference. When I dynamically allocated memory for array[50] in the run function, does that mean I am changing the size of the pArray in main as well? Or does the scope of array[50] ends with the function run? if so, should I do a delete [] Array inside the run function?
2. When I do delete[] pArray in main, what does it delete? memory for array[50]? or array[100]?
#include <iostream> using namespace std; void run(int* Array, int& s) { s = 50; Array = new int[s];
I am fairly new to dynamic memory allocation and I keep getting a segmentation fault in this code of mine. This is what the method should do:void sort StringsByReversePoints(char **myWords): This function sorts the char* values (i.e. strings) of myWords in descending order of point value by calling getWordPoints as a helper function and comparing adjacent words. This simple (but inefficient) sorting algorithm starts at the beginning of myWords array and sweeps to the end comparing adjacent values and swapping if they are out of order. After N (length of the array) sweeps the array is fully sorted. Note that efficiency can be improved by a factor of 2 by shortening each successive sweep by one, since the first sweep will have guaranteed the minimum point value word is the last element of the array, the next sweep guarantees the last two elements are correct, and so on....Additionally, if a given sweep results in zero swaps then the array is sorted and you can return immediately.
Why cant a dynamic memory allocation work with references? I was told that references work with const pointers deep down so shouldn't this be legal code?
int &&a=new int;
My compiler says that a entity of int* cannot be used to initialize a entity of int&&?
Does that mean that the compiler thinks of them as different types except deep down a reference is implemented with a pointer? Is this right?
I am using a pair of pthreads that call a pair of functions for ping-pong dma data transfer that are used in a loop for data transfer from an acquisition board. For a large # of waveforms, I ultimately run out of PC memory and the program stops. At the end of each function I use the delete[] command to clear memory for reuse, but the pointer appears to advance by the array size used for the transfer until the location exceeds the 2 GB I have for memory. I can see this happening using the Task Manager performance button time plot and window of total memory used continuing to increase to the limit. The culprit for one of the functions (2nd) is:
where pci_buffer1 and 2 have been set up and allocated in main. I also had the following line in each function process:
double* Rin = new double[length];
and it used up memory twice as fast. When I transferred the last line to an area just prior to main and used a constant 1024 for length, the program ran twice as far before exceeding system memory, so it appears that both lines were forcing new memory assignments and moving the pointers accordingly. In addition to using the delete[] command to free memory unsucessfuly at the end of each function procedure, I ended up closing the memory at the end of each procedure, then reallocating it again with the idea that the pointer would be set back to the original value, but it still seems to icrement along. So, neither approach appears to allow reuse of the memory because the pointer continues to march along. Using Visual C++ 6.0 to compile.
This is the question; Write a function that builds a two-dimensional multiplication table with arbitrary sizes for the two dimensions.
This is what I have done. I have allowed the user to input whatever size table they want by arbitrarily choosing what value they can input. However I cannot get the board to have blank squares. I thought the char would do it.
Code: #include <iostream> using namespace std; char SQAURE_CHAR = {' '}; const int Board_Size = 14;
I am working on an OOP assignment (text handler) which part of its description is:
Some lines of text as a story which the delimiter between each story is %%%%%
Each text loaded should only occupy the space needed for the text to fit.
It's required to use dynamic variables of type char*. To be more detailed, the text-handler must contain a vector of such char-pointers (i.e. c-strings), and the parameter in the constructor indicates how many pointers (c-strings) to be contained in the vector. Each loaded text will be represented by a number, so that the first text in the file gets number 0 and the next one gets number 1 ... etc. When you want to access a text, you request the text with a certain number, and then get a pointer in return that may be used to output the text on the screen.
My problem is first to allocate a dynamic memory like char** without defining the number of array elements (Each text loaded should only occupy the space needed for the text to fit. )and then store each story from text file (comprise of a few lines of text) into that dynamically located memory(char **)to be able to do some operation on it later.
Dynamic memory allocation in array in c programming. I am trying to make the user to choose the size of array they want to engage in the game.
However, i have remove the global variable which contribute the error to my code previously. Now I assigned all the arr individually but not using the global variable. However, i still not get the desired board i want. i still keep getting 9x9 array board.
And i also need limit the board size only from 4 to 9. And how do i do that.
Trying to append a comma to a string. Getting "Segmentation Error" on Solaris when the function is entered the second time.
Code:
// Appends a comma to the given string void appendComma(char* instring) { if (instring == NULL) { instring = realloc(NULL, strlen(",")); strcpy(instring,",");
I need to read lines from one file and copy them line by line into another file using dynamic memory allocation. It compiles but gives me a seg fault. Why/How?
I need to confirm that this problem cannot be solved without a pointer. Namely I need to read the rows and columns number from the user cin >> m, n and then use to declare an array int A[m][n];
However as m and n are not constants I am not able to do that. Is there a workaround? The following is the solution I came with BUT using a pointers which should be not the case.
// solution with using pointers as "int A[m][n]" does not work for me!!! void TwoDimensionalArrayFunc(){ int m = 0; int n = 0;
// instruct the users to enter array dimensions cout << "Please insert value for m:"; cin >> m;
I have a 1000 bytes global array (which did not dynamic allocated).
I need to make "dynamic allocation" from this array.
For example - MyMalloc(50) ---> The program will allocate 50 bytes OF THE ARRAY'S SIZE. ------ MyFree(pointer) ---> I need to check if the pointer is in the array and free the space.
It should be managed by blocks. The array should also contain the manage variables (for me).
I coded a program that takes some strings and lexicographically orders the strings and its substrings. I have used dynamic memory allocation technique and its working fine for all strings without consecutive same alphabets.I use a list in which a string is placed in its exact position by moving the others right.
When I run the program this is the output: Amy Adams 10111 97 86 78 95
-842150451 -6.27744e+066 -6.27744e+066 -6.27744e+066 -6.27744e+066 and so on .....
Press any key to continue . . .
As you can see the program is reading the first students information and outputting that fine, but the rest of the students have bad values for output. I'm guessing it's something to do with the pointer, but I really can't figure it out, why it won't read all of the students info?
i'm implementing a playerclass for a game.. in the game there are multiple player types, weapons ect.. i just wanted to turn my players weapons into a dynamically allocated c_str. once i added my: Destructor, Copy Constructor and Overloaded Assignment Operator. My initial values became corrupted and i cannot fix them.
I was doing a side programming challenge in my workbook that asked me to dynamically allocate and array for test scores. So far I have an array that will accept an integer to allocate the amount of test scores and then will accept integers to populate the array, however when I try to cout the contents of the array the numbers are absurdly different than what was put in. Here's my code:
#include "stdafx.h" #include <iostream> using namespace std; void main() { cout << "How many test scores?" << endl; int scores(0);
[Code] ....
And this is the output screen: How many test scores? 4 Enter test score 1: 22 Enter test score 2: 33 Enter test score 3: 44 Enter test score 4: 55 -33686019 18472 55656634 201345063 Press any key to continue . . .
Why am I getting these crazy numbers? I've looked back and forth from examples in my book and it doesn't look like I'm doing anything wrong.