简体   繁体   中英

How can I properly dynamically allocate memory for an "array" of strings

So, I'm just messing around with some code that asks the user how much personnel they'd like to hire. After entering the number they'd like, I initiate 3 pointers. The pointer I'm focused on is the string pointer "employee_Names". After initialization, I try and dynamically allocate the proper amount of memory required based on the user input to the pointer "employee_Names".

I think my syntax is good for that part, but my problems come when I try to actually store information in the memory allocated. As seen in the code, I try to directly set employee_Names[0] equal to a name, but that gives me errors.

personnel = requested_service() - 1;

string  *employee_Names;
int *employee_Ages;
char *employee_Company;

employee_Names = (string*)malloc(personnel);

employee_Names[0] = "Bahn";

printf("Employee number 1 is: %s", employee_Names[0]);

I would really love some enlightenment. Let me know if I need to be more specific in an area, or if more code needs to be seen.

The problem is that you used malloc() . You allocate memory for personnel number of bytes , not number of strings . And you don't construct any string objects in that memory at all.

Don't use malloc() in C++ at all, if you can avoid it. Use new and new[] instead, eg:

#include <string>
#include <cstdio>

personnel = ...;

std::string *employee_Names;
...

employee_Names = new std::string[personnel];
employee_Names[0] = "Bahn";
...

std::printf("Employee number 1 is: %s", employee_Names[0].c_str());

...

delete[] employee_Names;

That said, you really should use std::vector instead of new[] directly. Also, use std::cout instead of printf() :

#include <iostream>
#include <vector>
#include <string>

personnel = ...;

std::vector<std::string> employee_Names(personnel);
...

employee_Names[0] = "Bahn";
...

std::cout << "Employee number 1 is: " << employee_Names[0];

Lastly, given your variable names, consider using a class or struct to group an employee's details together:

#include <iostream>
#include <vector>
#include <string>

struct Employee
{
    std::string Name;
    int Age;
    char Company;
};

...

personnel = ...;

std::vector<Employee> employees(personnel);

employees[0].Name = "Bahn";
...

std::cout << "Employee number 1 is: " << employees[0].Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM