c++ - why does passing char[] not work, but (deprecated conversion) char* does? -


i cannot explain myself reason following behaviour. initialize 2 pieces of text, 1 char*, other char[] , put them structure. both appear fine in structure, in main, second 1 lost, , first gives me compiler warning understand (deprecated conversion string constant char*).

this first question ask here, , apologize done wrong. , yes, tried search, related char* , char[], there appear lot of q&a, none found similar nested problem having.

from attached code output:

get_struct: 5 test test2 main: 5 test 

(the test2 @ end missing)

so code:

    #include <iostream>       typedef struct {         double a_double;         char* a_char1;         char* a_char2;     } teststruct;      teststruct make_struct(double d, char* c1, char* c2) {                   teststruct t;          t.a_double = d;         t.a_char1 = c1;         t.a_char2 = c2;          return t;     }      void get_struct(teststruct &t) {             char* test_char1 = "test";         char test_char2[] = "test2";         double test_double = 5;          t = make_struct(test_double, test_char1, test_char2);          std::cout << "get_struct: " << t.a_double << " "              << t.a_char1 << " " << t.a_char2  << std::endl;     }      int main() {         teststruct t;         get_struct(t);         std::cout << "main: " << t.a_double << " "              << t.a_char1 << " " << t.a_char2 << std::endl;         return 0;     } 

you have problem in store pointers local variables in structure.

in case of test_char2 array, no longer exists once get_struct function returns. means pointer a_char2 no longer points valid string, , dereferencing pointer undefined behavior.

the reason first pointer works, because doesn't point local variable, points string literal, , stored elsewhere in memory.

when coding in c++, there no longer reason use pointers or arrays string, instead use std::string class.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -