+ 6
This is a good question. So The first function (getMessage) puts a c string into an array. Then returns​ the address of the array. Unfortunately the array is local, so the address is not valid once it's returned from the function. The second function (get other message) does the same thing, except that it creates a pointer that points to the address of the array and returns the pointer. The result is the same as the array is still local, the address is still not valid after it's returned from the function. The third function (getFinalMessage) again creates an array containing a c string. The array is still local, but this function uses strdup() to make a copy of the string, on the heap. The function returns a pointer to the copy on the heap, which is still valid after the function returns. (The function also does a check to see if the pointer is valid, ie if strdup () was able to allocate the memory. If it fails the function returns the address of a string literal, the error message. The string literal will be stored statically in the program, so this address will always be valid.) Once the main function is finished this string, free() is called release the memory of this string from the heap.
21st Jan 2018, 12:05 AM
Jared Bird
Jared Bird - avatar
+ 4
you know Mr.ace things like this get me confused,real fast,illd help if you explained it😂😂
20th Jan 2018, 8:44 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 2
Well they're supposed to return pointers for the first two. There's an idiosyncracy here since char* and char[] will work the same. However, correct me if I'm wrong, but the messages may be garbled because the memory wasn't allocated explicitly (malloc/calloc) and although the start address is returned, it is all within each function. This kinda renders the third function null-en-void, though the intention was to take advantage of how the addressing of a static string works: char* funct() { return "Hiya"; } (though the ? operator will return ptr a|ways) It's a little hacky because that memory can be overwritten. As far as I know it'll only work with 8bit chars because of addressing (each address is 1 byte). Most of this is guess work and speculation without my PC and compiler on hand. ...Hope I'm on the right track.
20th Jan 2018, 11:55 PM
non
+ 1
Ah, good work Jared. I missed strdup. Very lateral. So I was getting warm. Ace should be SL's personal quizz king.
21st Jan 2018, 10:21 PM
non
0
string function is character function which is used in character.
23rd Jan 2018, 3:18 PM
Aishwarya