我有一个继续递增图表的函数,因此它将显示ascii代码中的下一个字符,但我的问题是它永远不会打破循环
char * myFunction (char* &text)
{
char *temp = (char *)malloc(strlen(text));
char *tmp = temp;
while(*tmp != '\0')
{
*tmp = *text++; //im incrementing the text
tmp +=1;
}
return temp;
}
char *text = "hello";
cout<<myFunction(text)<<endl;
答案 0 :(得分:2)
while(tmp != '\0')
是
while(*tmp != '\0')
tmp
是字符串开头的地址,永远不会是'\0'
答案 1 :(得分:1)
您的代码中存在许多问题,我在下面的评论中对其进行了总结:
// Making your argument char*& allows you to modify text variable from
// calling function, I dont think this was your intention. If you just
// want to pass string to this function change its type to `const char*`.
// I dont think this return value you really want here, now you have char, but I
// suppose you want to return string, so it should be `char*` or `const
// char*`
char myFunction (char* &text)
{
// sizeof(text) will return 4bytes, which is size of pointer,
// you want strlen(text)+1 here to get length of string + 1
// char for zero (end of string)
char *temp = (char *)malloc(sizeof(text));
char *tmp = temp;
// You should dereference *tmp, but tmp is uninitialized here,
// I think you want to use *text here.
while(tmp != '\0')
{
*tmp = *text++; //im incrementing the text
// You are incrementing value pointed by tmp,
// if you want to increment tmp to next string
// element use tmp++;
*tmp +=1;
}
// Here assign zero to last element of text
// temp is char* and your return value is char, this is wrong,
// you should change return value of myFunction to char*. Also
// remember to call free() on returned string once its no
// longer needed - otherwise you will introduce memory leaks
return temp;
}
// This should be `const char *text = "hello";` In c++ string
// literals are of type `const char*`
char *text = "hello";
cout<<myFunction(text)<<endl;