Think of it this way: when you allocate memory for the struct, you get the pointer member variables for free. So in essence, when you do this:
mystruct *s = malloc(sizeof(mystruct)); //don't cast result of malloc.
Then you can treat s->str1 in the exact same way as you would any regular char* variable, say
char *str1 = NULL;
If you want it to point to something, then you have to allocate memory for the pointers. Consider this:
mystruct* mystruct_new(const char* str1, const char* str2){ mystruct *s = malloc(sizeof(mystruct); char* someString = getMyString(); //gets some arbitrary string char* str1 = NULL;//just for demonstration int length = strlen(someString) + 1; //for struct members s->str1 = malloc(sizeof(char) * length); strcpy(s->str1, someString); //For regular pointers str1 = malloc(sizeof(char) * length); strcpy(str1, someString); return s; }
Also note that if you just assign to a pointer by using the = operator instead of allocating memory, then it will only copy the address to the original value. This may or may not be what you want depending on the context. Generally, if you know the memory location will stay in scope and you don't need (or don't mind) to change the original string, then it is preferred to simply assign it. Otherwise, it is advisable to make a copy.
//Makes a copy of the string s->str1 = malloc(sizeof(char) * length); strcpy(s->str1, someString); //copies the address of the original value only! s->str1 = someString;
strdup(str1). We would need to see how this function is called to emit an advice. with string literals your code is fine.mystruct_new(...). Instead, it would point to the exact same string as you passed in. So if you callmystruct_new(inputStr1, inputStr2);, and then change inputStr1, e.g.inputStr1[0] = 'b', it would also change your mystruct's str1.str1isn't local to the function, so it would not be destroyed at the end of the function, but its scope is unknown. If it was scoped inmain, for example, it would would survive to the end of the program. But depending on what exactly it is, maybe it would be changed and that change would affect your struct sinces->str1would be pointing to it rather than having its own copy.