[英]pointer to string that can be used to dynamically allocate array of strings
[英]How can I properly dynamically allocate memory for an "array" of strings
所以,我只是在處理一些詢問用戶他們想要雇用多少人員的代碼。 輸入他們想要的數字后,我啟動了 3 個指針。 我關注的指針是字符串指針“employee_Names”。 初始化后,我嘗試根據用戶對指針“employee_Names”的輸入動態分配所需的適當內存量。
我認為我的語法適合那部分,但是當我嘗試在分配的內存中實際存儲信息時,我的問題就出現了。 如代碼所示,我嘗試直接將employee_Names[0] 設置為等於姓名,但這給我帶來了錯誤。
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]);
我真的很喜歡一些啟蒙。 如果我需要在某個領域更具體,或者是否需要查看更多代碼,請告訴我。
問題是您使用了malloc()
。 您為personnel
字節數而不是字符串數分配內存。 並且您根本不在該內存中構造任何string
對象。
如果可以避免的話,根本不要在 C++ 中使用malloc()
。 使用new
和new[]
代替,例如:
#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;
也就是說,你真的應該直接使用std::vector
而不是new[]
。 另外,使用std::cout
而不是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];
最后,給定您的變量名稱,請考慮使用class
或struct
將員工的詳細信息組合在一起:
#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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.