I was wondering if it was okay to pass around/return structs holding statically allocated arrays in C++. For example:
typedef struct t{
char name[32];
int id;
}t;
t foo(char name[]){
t my_t = {name, 0};
return my_t;
}
int main(){
t main_t = foo("a struct");
printf("%s", main_t.name); //is this safe to access?
return 0;
}
When it returns the struct by value, I guess it doesn't copy the array name, only the pointer to it.
Edit: Just to clear up some things. I do know that char *var
is equal to char var[]
in function arguments. I wrote this code up really quickly without even testing it. I know it is definitely not the best code in the world and I wouldn't advice anybody to use it in real life.
Ideally I would allocate the struct dynamically and pass around a pointer, however, I am teaching a person to program in C/C++. It is for a national exam which doesn't require a person to know dynamic allocation or pointers for that matter, that is why *
are not really used at all.
The question is really about whether it is okay to return a struct holding a statically allocated array.
Shall we use this piece of code instead:
#include <iostream>
struct t{
char name[32];
int id;
};
t foo(int id){
t my_t;
my_t.id = id;
for(char i = 0; i < 31; i++){
my_t.name[i] = 'a';
}
my_t.name[31] = '\0';
return my_t;
}
int main(){
t main_t = foo(0);
std::cout << main_t.name; //is this safe to access?
return 0;
}