BRe*_*ves 2 c reference function char dereference
季节的问候!我有一个函数打印出char**的内容,它被用作存储多个字符串的数组.声明如下:
char** commandArray = (char**)malloc(historySize);
Run Code Online (Sandbox Code Playgroud)
其中historySize是一个全局int设置为8,目前.该数组使用用户输入的命令填充,排序为循环队列.有几个地方我可能想要打印出缓冲区的内容,所以我做了一个功能.理想情况下,该函数接受commandArray的引用并循环遍历它,打印出它包含的内容.现在,我不得不说指针和引用不是我的强项,所以我不确定我是否正确地做事.该函数如下所示:
/* prints the contents of the history buffer */
void printHistory(char*** historyBuff)
{
/* a counter for the loop */
int loopIdx = 0;
for (loopIdx = 0; loopIdx < historySize; loopIdx++)
{
/* print the current history item */
printf ("\nhistoryBuff[%i] = %s\n", loopIdx, *historyBuff[loopIdx]);
fflush(stdout);
}
}
Run Code Online (Sandbox Code Playgroud)
我将我的char**传递给这样的函数:
printHistory (&commandArray);
Run Code Online (Sandbox Code Playgroud)
现在看来,一切都编译得很好,但是当程序打印出历史记录时,该函数会挂起循环中的某个位置并且不会打印出char**中的内容.所以,我的问题是:我正确地传递commandArray,我是否正确地声明了函数,我是否正确地在函数中取消引用它?
提前感谢您提供任何帮助或建议!
-ben
要使代码按原样运行,您应该取消引用:
(*historyBuff)[loopIdx]
你写的东西的方式,因为C中的运算符优先级而[]发生*,并且它不是你想要的.
您需要为命令数组分配更多空间.现在它实际上并不足以容纳historySize char*:
char** commandArray = (char**)malloc(historySize * sizeof(char*));
Run Code Online (Sandbox Code Playgroud)您不需要通过"reference"传递此数组.您可以像这样声明您的函数:
void printHistory(char** historyBuff)
Run Code Online (Sandbox Code Playgroud)
并commandArray直接传递.char***如果你打算在函数中的某个地方更改实际的数组指针,你只需要传入一个(例如,如果你需要realloc它来增加空间).
对于只打印东西的功能,你可以更进一步宣传const.这是调用者的"保证"(只要你可以保证C中的任何内容),你不会修改数组或其中的字符串:
void printHistory(const char *const * historyBuff)
Run Code Online (Sandbox Code Playgroud)