How to mimic C++ "pass array(pointer) by reference" in C? -
sorry cryptic title, i've searched answer, couldn't find one. anyway, i'm trying pass char array function , modify pointer inside array. here example of mean in c++:
#include "stdio.h" #include "string.h" void fill(char*& destination, const char* const input, int size) { memcpy(destination, input, size); destination += size; } void inner(const char* const string1, int size1) { const int size2 = 8; char string2[size2] = "world!\n"; char output[20]; char* outputwriter = output; fill(outputwriter, string1, size1); fill(outputwriter, string2, size2); printf(output); } int main() { inner("hello ", 6); }
which outputs hello world!
and here attempt in c:
#include "stdio.h" #include "string.h" void fill(char** const destination, const char* const input, int size) { memcpy(destination, input, size); *destination += size; } void inner(const char* const string1, int size1) { const int size2 = 8; char string2[size2] = "world!\n"; char output[20]; char (*outputwriter)[20] = &output; fill((char**)outputwriter, string1, size1); fill((char**)outputwriter, string2, size2); printf(output); } int main() { inner("hello ", 6); }
which outputs _orld!
, , casting not pretty.
what correct way pass such pointer array function in order able modify similar c++ code does?
this after:
#include "stdio.h" #include "string.h" void fill(char** destination, const char* const input, int size) { memcpy(*destination, input, size); *destination += size; } void inner(const char* const string1, int size1) { const int size2 = 8; char string2[size2] = "world!\n"; char output[20]; char* ptr = output; fill(&ptr, string1, size1); fill(&ptr, string2, size2); puts(output); } int main() { inner("hello ", 6); }
Comments
Post a Comment