如何模仿C ++"通过引用&QUOT传递数组(指针);用C? [英] How to mimic C++ "pass array(pointer) by reference" in C?
本文介绍了如何模仿C ++"通过引用&QUOT传递数组(指针);用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉的神秘称号,我搜索了一个答案,但没能找到。无论如何,我想一个字符数组传递到一个函数和修改数组内的指针。这里是我的意思在C ++的例子:
Sorry for the cryptic title, I've searched for an answer, but couldn't find one. Anyway, I'm trying to pass a char array into a function and modify the pointer inside the array. Here is an example of what I 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);
}
它输出的Hello World!
这是我尝试在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);
}
它输出 _orld!
,和铸造是不是很pretty。
Which outputs _orld!
, and the casting is not very pretty.
什么是这样的一个指针数组传递给函数,以便能够修改它类似于C ++ code做什么?
What is the correct way to pass such a pointer to an array to a function in order to be able to modify it similar to what the C++ code does?
推荐答案
这是你所追求的:
#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);
}
这篇关于如何模仿C ++"通过引用&QUOT传递数组(指针);用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文