有很多的代码中的问题,我总结他们在下面的评论:
// 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;
* TMP + = 1; - > tmp + = 1; – songyuanyao
更好的使用字符串函数,如[strlen](http://linux.die.net/man/3/strlen)(而不是'sizeof(text)',这将不起作用,除非你想要的大小指针本身)和[strcpy](http://linux.die.net/man/3/strcpy)(而不是手动循环)。另外,不要假设[malloc](http://linux.die.net/man/3/malloc)成功,_always_检查它的返回值(这里是'temp')! – Jens
如果'* text ++'返回''\ 0''那么* tmp + = 1;将增加它 – rajenpandit