Returning Local Arrays in C : Avoiding Warnings
Returning local arrays in C can trigger a warning like "returning address of local variable or temporary." To address this issue, consider an alternative approach that alleviates this warning:
Using std::vector
In C , using std::vector
std::vector<char> recvmsg() { std::vector<char> buffer(1024); //.. return buffer; } int main() { std::vector<char> reply = recvmsg(); }
By using std::vector
Accessing char* if Needed
If you still require a char* for C API compatibility, you can access it with &reply[0]. For instance:
void f(const char* data, size_t size) {} f(&reply[0], reply.size());
This allows you to use std::vector while still interfacing with C APIs that require char* parameters.
Benefits of Avoiding new
Employing std::vector avoids the use of new, which has the following benefits:
Conclusion
Using std::vector
The above is the detailed content of How Can I Safely Return Local Arrays in C Without Warnings?. For more information, please follow other related articles on the PHP Chinese website!