【发布时间】:2014-11-04 16:10:35
【问题描述】:
我正在创建一个(非常)基本的 shell - 但是,我是在随意使用函数来更改全局变量的基础上进行的 - 年长和聪明的程序员建议我不要这样做 - 所以我已经着手改变这种行为返回指向变量的指针,而不是更改全局变量。
当我的程序运行 getline 时,读取数据的指针返回空,导致它在我稍后获取字符串的副本时崩溃。我知道 getline 工作正常 - 但是离开方法时结果会丢失。为什么会这样,我该如何解决?
非常感谢!
#define TRUE 1
#define FALSE 0
int readcmd(char* cmd, size_t nBytes);
int argCount = 0; //Counter of number of arguments
int readcmd(char *cmd, size_t nBytes) {
int ret = getline(&cmd, &nBytes, stdin);
printf("%s", cmd); //This prints correctly
return ret;
}
int main() {
const size_t nBytes = 64; //Data type representing size of objects (unsigned)
char *cmd = NULL; //Pointer to input string
char *cmdCpy = NULL;
int bytesRead = -1;
char prompt[] = "DaSh-> ";
while (1) {
printf("%s", prompt); //Print prompt
bytesRead = -1;
while (bytesRead == -1) {
bytesRead = readcmd(cmd, nBytes); //While no bytes read, loop
}
printf("%s", cmd); //This prints "(null)" - data lost!?
cmdCpy = malloc((sizeof(char) * bytesRead) + 1);
strcpy(cmdCpy, cmd);
return 0;
}
}
【问题讨论】:
标签: c function pointers getline