C++ :: Dynamically Expanding Array
May 28, 2013
Consider the following:
Code:
int *p;
p = new int[5];
for(int i=0;i<5;i++)
*(p+i)=i;
Now suppose we want to add a 6th element (without using vector)
One way is to copy it across to a larger array:
Code:
int *p;
p = new int[5];
for(int i=0;i<5;i++)
*(p+i)=i;
// realloc
int* temp = new int[6];
std::copy(p, p + 5, temp);
delete [] p;
p = temp;
This looks like a very expensive operation and im looking for other ways.
Three questions regarding the above: Not using vector, is this the best way to do this?What about using realloc? How would I use realloc in this situation?Any other ways apart from realloc or vector?
View 1 Replies
ADVERTISEMENT
Jun 3, 2013
I have the following struct array list...
Code:
typedef struct ArrayList {
char **array;
//number of elements inside list
int elements;
//length of array
int maximum;
}
ArrayList; I've already created a pointer to ArrayList called "mylist" but this list only has a size of int maximum =10....I want to be able to call expand ArrayList in one of my functions incase I need to make my list greater than the size I already allocated for it. expandArrayList(myList, myList->maximum*2+1); is what I would call inside of my function if I needed to expand the list and here is my actual function...
Code:
ArrayList *expandArrayList(ArrayList *myList, int length) {
int i;
char **newArray;
myList->array=malloc(sizeof(char*)*length);
[code]...
I need this code to allocate a new array of length, which would now be 21. Then I need to copy the contents of the lists old array into the new array...Which I am very confused on this part... I created a temporary char **newArray but I don't know if its even taking any of the strings in. I then need to point the old list->array to the newly created array, update all of the values for elements and maximum and then return a pointer to ArrayList... I've tried a bunch of different code and nothing seems to be expanding my original list at all.
View 2 Replies
View Related
Feb 1, 2013
I'm trying to expand a template + argument parameter list inside a lambda function like this:
template <typename Class, typename ...Args>
static void create(Args ...args) {
// Perform pre-thread creation work.
std::thread([=]()
[Code] ....
But this does not work:
The compiler error is "error: parameter packs not expanded with ‘...’:|"
However, when I do the following:
template <typename Class, typename ...Args>
static void create(Args ...args) {
// Pre-thread work.
auto tthr = [](Args ...ar) -> void {
[Code] ....
It works just fine. That shows that lambda threads are able to take variadic arguments...
So here is my question; what is the correct capture clause for capturing the variadic object correctly?
View 3 Replies
View Related
Jan 18, 2014
I'm trying extremely hard to understand pointers and I have the basic concept down.. I feel as though my knowledge of dynamically allocated pointers and pointers in general is not enough to understand the logic behind what I'm trying to do. The problem is that the donations array must be able to accept any number of donations. I've made it do just that, but there is also an array of pointers which must each point to the same element in the donations array. The program works if I assign int *arrPtr[100] for example, but it does not work if I try to dynamically allocate it to accept the same number of elements for donations entered by the user. Here it's the snippet
#include <iostream>
using namespace std;
//Function Prototypes
[Code]....
View 2 Replies
View Related
Dec 18, 2014
I would like to realloc a 2D array. I have a counter, itime, it increases each step. Each step, I would like to reallocate my array, keeping the old values, and add new values to the array. When itime=1, I use only malloc, because it is allocated for the first time. When itime increases (e.q. itime=2), realloc comes into process. In the realloc process the GUI crashes.
int itime;
char ** solpointer;
itime = 1;
do {
if( itime == 1 ) {
solpointer = (char**)malloc(sizeof(char*) * itime);
solpointer[itime-1] = (char*)malloc(sizeof(char) * 32);
[code]....
View 3 Replies
View Related
Sep 8, 2014
I am working on expanding an array and my approach was to do this by copying the array into a bigger array. For this problem I cannot use vectors so what I did was the following:
int *a;
a = new int[5];
for(int i=0;i<5;i++)
*(a+i)=i;
// reallocating array
int* temp = new int[6];
std::copy(a, a + 5, temp);
delete [] a;
a = temp;
Is this approach correct, also how could I implement this on a program to expand an array to double its size or could I not use this to expand an array to double its size?
View 2 Replies
View Related
Nov 24, 2013
Working on this one from the Jumping into c++ book. The book asks that I create a multidimensional array at run time based on user input and fill it with a multiplication table
My code compiles fine but throws an uninitiated error for p when I try and run it.
Code:
void multiDimentionalMultiplication(int x, int y, int z){
int ***p;
**p = new int[x];
std::cout << "Allocating array.
[code]....
View 8 Replies
View Related
Jul 26, 2014
I want to access the elements of my array dynamically. So far I've only figured out how to do this manually. if I tried it like this my code would work but there should be a better way right?
View 10 Replies
View Related
Dec 2, 2013
I have declared an array like:
/***********Creating an m*p array**********************/
B = new int *[m];
for(row=0;row<m;++row)
B[row] = new int[p];
How to find the number of elements in it?
The statement
cout << "number of elements in array B equals " << sizeof(B) << endl;
returns 4 each time the program runs
View 3 Replies
View Related
Jun 14, 2013
I am trying to figure out the syntax to dynamically allocate a single dimension of a triple dimensional array. Basically i have a 2D array of structs. but each struct is an array (basically rows of the information). The rows of this structure need to be allocated dynamically, but the height and width of the overarching structure are static.
Basically: Struct * ts_FieldInfo[100][100] = new Struct[Class.returndataitems()];
View 2 Replies
View Related
Jul 26, 2014
I know I can allocate it this way, on the stack:
char* str[5];
for(i = 0; i < 5; ++i) {
str[i] = new char[STR_SIZE];
}
But if I want to allocate array size through 'new', what's the syntax for that?
I thought this might work, but it gives error: "Initialization with {...} expected for aggregate object"
char* newString[] = new char[5][ARRAYSIZE];
View 6 Replies
View Related
Oct 4, 2014
I have changed my const global int NUMLABS to a non constant variable so that the user can decide how many labs to input. I adjusted the parameters of each function to add NUMLABS becuase the variable is no longer constant. But now main() returns 0 right after the user chooses how many stations to put in each lab. I am having difficulty understanding these dynamically allocated arrays.
/*********************************************************************
Lab4.cpp
This program uses dynamic arrays to store login information for four labs. Each of the four labs is referenced by the labs[] array which is indexed from 0-3. A pointer in the labs[] array then references a dynamic array that is of size for however many computers are in that lab.
Written by: Luca Del Signore
Last modified on: October 3rd
Known bugs: N/A
*********************************************************************/
#include <iostream>
#include <cstdlib>
using namespace std;
[Code]....
View 1 Replies
View Related
May 2, 2014
class Album{
private:
char albumName[100];
Song* List;
int numSongs;
public:
Album(char*);
~Album();
[Code] ....
And everytime I create the class it can have only one song because I set numSongs to zero.
View 2 Replies
View Related
Apr 15, 2014
so I have this code that dynamically allocates a pointer array increasing and removing elements of the array as its operated on.then it sorts and prints out the array when the user is finished operation on the array. i get this error message when running the program though.
"Unhandled exception at 0x0F474F98 (msvcr110d.dll) in Lab10_VarArray.exe: 0xC0000005: Access violation reading location 0xCCCCCCC0."
this is my code
#include <iostream>
#include <cstdlib>
#include "Header.h"
using std::cout; using std::endl; using std::cin;
int main(void) {
char op='x';
[Code]...
View 3 Replies
View Related
Apr 6, 2014
I have a structure, containing a pointer as a member. I dynamically create an array of that structure type, and then need to dynamically create an array for its pointer member.
#include <iostream>
#include <string>
using namespace std;
[Code]....
There is more of my program afterwards, but it shouldn't matter. The errors I am getting at compile time are that I cannot convert an int pointer to an int (line 29) and that test is not a member of CourseGrade (lines 44/45).
My thought is I might be using the * operator incorrectly. My code before hand in line 29 was
for (i = 0; i < numberStudents; i++)
*studentPtr[i]->tests = new int[numberTests];
but the compiler suggested a '.' rather then the '->'
View 8 Replies
View Related
Aug 31, 2014
Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered by the user, the array must be passed to a function that sorts them in ascending order. It must use another function that calculates the average score. The program should display the sorted list of scores and average with appropriate headings. The program must use pointer notation instead of array notation. Validation: Do not accept negative numbers for test scores; keep prompting the user for a new grade. Do not accept negative numbers for the number of scores the user wants to enter.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
double getAverage(int*, int);
void sortScore(int *,int );
[Code] ....
I have no errors in my code but when i run it and i enter a positive interger it just goes into a loop to enter a positive number.
View 2 Replies
View Related
Feb 4, 2015
I'm working the 4th problem in chapter 14 of the Jumping into C++ book. In the book, he gives an example program for dynamically resizing an array while the program is running. It works fine for integer types but i need to do the same with a string type array. Right now my program is crashing because the string array is not resizing itself. Here's the part of the code im trying to figure out. The part for the int array has been ignored using // since it works fine and I'm trying to figure out whats wrong with the string array.
Code:
#include <iostream>
#include <string>
//Write a program that lets users keep track of the last time they talked to each of their friends.
//Users should be able to add new friends (as many as they want!) and store the number of days ago
[Code]......
View 8 Replies
View Related
Apr 20, 2013
This is a homework assignment where I have to read a file into a dynamically allocated 2d array. The file format is
10
Jim 3.6
Jake 4.0
Will 3.0
Sara 3.4
Mike 2.5
Ellen 2.9
Melissa 3.9
Eric 3.8
John 3.5
Beth 3.9
where 10 is the number of students followed by the students and the gpa's. There is more to the program but I have not implemented it yet because I am getting a segmentation fault. The output I am getting when I print the array is
Jim 3.6
Jake 4.0
Will 3.0
Sara 3.4
Segmentation fault
I can see where the problem lies. If I raise value for row when I am allocating the rows of the array, all of the names print. I just do not see why I need to. From my understanding the row * sizeof(char*) should give me enough room for 10 entrie.
Code:
#include <stdio.h>
#include <stdlib.h>
void sort();
int main()
[Code] .....
View 6 Replies
View Related
Jun 22, 2013
Suppose I wished to initialize a dynamically allocated array of integers to zero. Would I do better to use calloc() or malloc + iterate over all entries setting each to zero? Which one is regarded as a better approach?
View 12 Replies
View Related
Jul 15, 2013
Code:
void readFile(struct course *d, char* filename){
FILE* fp;
char buffer[100];
int i = 0, array_size = 100;
struct course *temp;
[code]....
I will be using this to read data from a file. I start with an array of 100 structures being passed to the readfile function. Once it reads 100 lines (i == array_size), I want to double the array size until I have finished reading the file.
Two questions.
1)My initial thought was that I needed to keep track of the lines read with my variable, i. However, is there a better way?
2)My program is crashing right now at the call to double_array_size function. What is wrong with my code? Never dealt with dynamically allocated array of structures and functions.
I read online that I should change my code in the following manner.
Code:
void readFile(struct course *d, char* filename) {
FILE* fp;
char buffer[100];
int i = 0, array_size = 100;
struct course *temp;
[code]....
I can paste the "error messages" if you like, but it is a page full of stuff I have never seen. glibc detected, Backtrace, Memory Map, and a bunch of numbers and hexadecimal stuff like addresses.
View 12 Replies
View Related
May 4, 2013
I'm trying to read in a file and store it in an array that is dynamically allocated of a struct (which I'm not sure how to do), then parse each line using strtok() from string.h. The idea is to separate the lines by date, subject, time, etc.
Since the array is a dynamically allocated of typdef struct, it's sorted by the date of each struct, with an intial size of 25. But whenever the array needs to be resized, it should be doubled.
View 1 Replies
View Related
Oct 5, 2014
this is my function for allocating memory in 2D array
Code:
#include <stdio.h>
#include <stdlib.h>
int allocate_array(int **array, int *row, int *column){
int i;
}
[code]....
end of allocate_array function and this is my function for asking for the values to be stored in array
Code:
int input_array(int **array, int row, int column){
int i, j;
//ask for the values to be stored in the 2D array
for( i = 0; i < row; i++ ){
for( j = 0; j < column; j++ ){
}
[code]....
why I'm having error here in my input_array() function
Code: scanf("%d", &array[i][j]);
View 2 Replies
View Related
Dec 13, 2013
I would like to know if this code is correct.
#include <iostream>
#include <string>
int say_one(const std::string &s) {
std::clog << s << ": One!
[Code] .....
View 7 Replies
View Related
Sep 18, 2014
How can I return a dynamically allocated 2d array from a function? Do I use like this:
int main(){
char **array;
array=func();
} char ** func(){
char** ptr=new char[5]; //five words
ptr[0]=new char[size of word1];
*ptr[0]=word1
........
return ptr;
}
View 8 Replies
View Related
Jan 12, 2013
Just trying to fill a dynamically allocated array with values then I want to print out the values using pointer method:
#include <iostream>
using namespace std;
long * extend_arr(long int arr[], long int length, long int val) {
long * array2 = new long [length + 1];
for (int J = 0; J < length; ++J)
array2[J] = arr[J];
[Code] ....
When this runs, I get an array with random numbers in it. For example, just trying to print the first value in *Block gives me random numbers each time. What is wrong with this as to why it is not holding the right values?
The extend_arr works perfectly fine, because when I try to access the values in the array using indexes (arr[0], arr[1], etc) it shows the right output, but using pointers does not. How can I make it work?
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 134561 23 29 640 112
As you can see, the primes end at 97 but it just keeps printing more
It now prints the correct values in the function if I set the last value in the array to 0. arr[length] = 0;
Now if I wanted to print the values in the array within main, why is that not working?
Nvm, I just changed the void function to return a pointer to an array.
View 2 Replies
View Related
Jul 27, 2014
This a very simple program I created because I dont understand how do this. My goal is to be able to use the pointer *s5 throughout the program. For example I would to like to call other functions and pass that pointer through the function. I understand the dynamic allocation and pointers for the most part but Im confused here because the "new char[20]" variable will die after the function and I dont want it to.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
void testArray ( char *s5 );
int main ( int argc, char *argv[] )
[Code] .....
Also does strlen count the null terminator?
View 1 Replies
View Related