Using C++11:
std::set<std::string> str = {"John", "Kelly", "Amanda", "Kim"};
Otherwise:
std::string tmp[] = {"John", "Kelly", "Amanda", "Kim"};
std::set<std::string> str(tmp, tmp + sizeof(tmp) / sizeof(tmp[0]));
std::set<std::string> str = {"John", "Kelly", "Amanda", "Kim"};
std::string tmp[] = {"John", "Kelly", "Amanda", "Kim"};
std::set<std::string> str(tmp, tmp + sizeof(tmp) / sizeof(tmp[0]));
#include <stdlib.h>
#include <stdio.h>
void create_array (int* data, int size)
{
data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}
print_array(data, size);
}
void print_array (int* data, int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", data[i]);
}
printf("\n");
}
int main (void)
{
int* data;
const int size = 5;
create_array(data, size);
print_array(data, size); // crash here
free(data);
}
print_array is called from inside the create_array function, I get the expected output 0 1 2 3 4, but when I call it from main, I get a program crash.#include <stdlib.h>
#include <stdio.h>
void print_array (int* data, int size)
{
for(int i=0; i<size; i++)
{
printf("%d ", data[i]);
}
printf("\n");
}
void create_array (int* data, int size)
{
//data = malloc(sizeof(*data) * size);
data = (int *) malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}
print_array(data, size);
}
int main (void)
{
int* data;
const int size = 5;
create_array(data, size);
print_array(data, size); // crash here
free(data);
}
data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller.void func (int x){
x = 1;
printf("%d", x);
}
...
int a;
func(a);
printf("%d", a); // bad, undefined behavior - the program might crash or print garbage
a is stored locally inside the function, as the parameter x. This is known as pass-by-value.x is modified, only that local variable gets changed. The variable a in the caller remains unchanged, and since a is not initialized, it will contain "garbage" and cannot be reliably used.data is passed by value to the function. The data pointer inside the function is a local copy and the assigned address from malloc is never passed back to the caller.create_array function has also created a memory leak, since after that function execution, there is no longer any pointer in the program keeping track of that chunk of allocated memory.int* create_array (int size)
{
int* data = malloc(sizeof(*data) * size);
for(int i=0; i<size; i++)
{
data[i] = i;
}
print_array(data, size);
return data;
}
int main (void)
{
int* data;
const int size = 5;
data = create_array(size);
print_array(data, size);
}
void create_array (int** data, int size){
int* tmp = (int *) malloc(sizeof(*tmp) * size);
for(int i=0; i<size; i++)
tmp[i] = i;
*data = tmp;
print_array(*data, size);
}
int main (void){
int* data;
const int size = 5;
create_array(&data, size);
print_array(data, size);
}