C 通过引用将字符**传递给函数
祝你节日快乐!我有一个函数,它打印出一个字符**的内容,该字符**被用作一个数组来存储许多字符串。声明如下:C 通过引用将字符**传递给函数,c,function,reference,char,dereference,C,Function,Reference,Char,Dereference,祝你节日快乐!我有一个函数,它打印出一个字符**的内容,该字符**被用作一个数组来存储许多字符串。声明如下: char** commandArray = (char**)malloc(historySize); 其中historySize是一个全局整数,暂时设置为8。数组中填充了用户输入的命令,类似于循环队列。我可能需要打印出缓冲区的内容,所以我做了一个函数。理想情况下,该函数接收对commandArray的引用,并在其中循环,打印出它所包含的内容。现在,我不得不说,指针和引用不是我的强项,所
char** commandArray = (char**)malloc(historySize);
其中historySize是一个全局整数,暂时设置为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);
}
}
printHistory (&commandArray);
void printHistory(char** historyBuff)
现在,一切都可以编译,但当程序打印历史记录时,函数挂起在循环中的某个位置,不会打印出char**中的内容。所以,我的问题是:我是否正确地传递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);
}
}
printHistory (&commandArray);
void printHistory(char** historyBuff)
(*historyBuff)[loopIdx]
按照您编写东西的方式,[]
发生在*
之前,这是因为C中的运算符优先级,而这不是您想要的historySize
char*
:
char** commandArray = (char**)malloc(historySize * sizeof(char*));
/* 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);
}
}
printHistory (&commandArray);
void printHistory(char** historyBuff)
并直接传入commandArray
。如果要更改函数中某个位置的实际数组指针(例如,如果需要realloc
it以腾出更多空间),则只需传入char***
const
。这是对调用者的“保证”(只要你能保证C语言中的任何东西),你不会修改数组或其中的字符串:
void printHistory(const char *const * historyBuff)
malloc
分配大量字节,而不是指针。如果historySize
是您正在分配的字符指针数,则需要更改:
char** commandArray = (char**)malloc(historySize);
致:
2.
您的
printHistory()
不会更改commandArray
指针。您不需要传递字符***
。一个char**
就可以了。谢谢你们两位的帮助!该功能现在运行良好。我再次非常感谢。