通过引用调用一个双字符串的字符串
问题描述:
嗨,大家好我有一些使用一个函数引用一个字符串作为参数的问题。我读过你应该使用e双指针来做这件事,但我无法让它工作。 这是(部分)我的代码。通过引用调用一个双字符串的字符串
enum errCode { ERR_NONE = 0, ERR_EMPTY, ERR_FULL, ERR_MEM, ERR_INIT, ERR_COMMAND, ERR_UNDEFINED };
typedef enum errCode ErrCode;
typedef enum {
no = 0, add, del, src, show, exit
} Command;
int main(void) {
char stringval[50];
char stringval2[50];
ErrCode err;
Command currentCommand = no;
printf("Enter a command\n");
if (fgets(stringval, 50, stdin) != NULL) {
char *p;
if ((p = strchr(stringval, '\n')) != NULL)
*p = '\0';
}
ErrHandler(
extractCommand(¤tCommand, stringval, &stringval2)
);
printf("stringval 2 = %s.\n", stringval2);
return 0;
}
ErrCode extractCommand(Command *command, char *inputString, char **outputString) {
char *strTemp;
char *strTemp2;
//Get the first word of the string
strTemp = strtok(inputString, " ");
strTemp2 = strtok(NULL, " ");
*outputString = strTemp2;
//Check if it equals a command
if (strcmp(strTemp, "exit") == 0) {
*command = exit;
return ERR_NONE;
} else if (strcmp(strTemp, "add") == 0) {
*command = add;
return ERR_NONE;
} else if (strcmp(strTemp, "del") == 0) {
*command = del;
return ERR_NONE;
} else if (strcmp(strTemp, "src") == 0) {
*command = src;
return ERR_NONE;
} else if (strcmp(strTemp, "show") == 0) {
*command = show;
return ERR_NONE;
} else {
*command = no;
printf("%s", strTemp);
return ERR_COMMAND;
}
}
这是我的输出是什么样子:
Enter a command
add this is a test
stringval 2 = z˜ˇøÀo‡èK‡èT¯ˇø.
我显然希望有输入字符串的第二个字,但我做错了什么。 Thx求救!
答
stringVal2
没有初始化,也没有填充:这是原因垃圾正在打印。在这种情况下不需要通过char**
,通过char*
就可以工作。然而,这样的:
outputString = strTemp2;
不复制的strTemp2
到outputString
内容:它使outputString
指向同一个地址为strTemp2
:使用strcpy()
。
甲双指针,char**
例如,通常传递给功能时函数分配对于参数一个新的缓冲液(其不是在贴码的情况下):
char* buf = NULL;
my_alloc(&buf);
void my_alloc(char** p)
{
*p = malloc(10);
}
AREN你没有得到任何编译器警告?尝试使用-Wall选项编译并让我们知道警告消息是什么。 – 2012-04-15 21:47:47
这甚至不应该编译。 '&stringval2'是一个指向数组的指针,而不是指向指针的指针 – newacct 2012-04-16 00:27:16