0

For a project I am working on I need to have a global array of entry structs. I am having trouble though because I can't allocate memory until while running my program I determine the size of a file. The overall goal of this project is to create a word reference. So far how I am doing it is:

struct info{
   //stores the specific character
   std:: string c;
   //stores the amount of times a word has come up in the file
   float num;
}
info info_store[];

This project is to learn about arrays so I need to use an array

3
  • 2
    Use an std::vector. Commented Feb 9, 2018 at 4:52
  • I forgot to mention I need to use an array Commented Feb 9, 2018 at 5:03
  • 2
    ... Why? Is this homework or something? Commented Feb 9, 2018 at 5:03

2 Answers 2

1

You can:

- use new/delete[]

info* p_array=new info[100];  // create an array of size 100

p_array[10].num;  // member access example

delete[] p_array; // release memory

- use std::unique_ptr

std::unique_ptr<info[]> array(new info[size]);

-> The advantage is that your memory is automatically released when array is destroyed (no more delete[])

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, use std::vector or any other STL container.

Second, you can use dynamic arrays.

auto length = count_structs(file);
auto data = new info[length];

Something like this. Then just fill this array.

Ohh, and make sure you have delete [] data to prevent memory leaks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.