我目前正在从头开始编写strstr。在我的代码中,我正在索引一个字符串,并且我最终需要使用另一个指针来保存该字符串上的一个特定点。以下是我正在努力处理的代码部分:
char *save_str;
for(int i=0;i<length_str1; i++)
{
if(str1[i]==str2[0])
{
*save_str=str[i];然而,它告诉我我不能这样做。如何让指针指向索引中的特定字符?
发布于 2012-02-17 07:05:44
快速实用答案
save_str = &str[i];扩展描述性枯燥答案
在“纯c”和"c++“中有一个关于数组和指针的特性。
当程序员想要整个数组的地址或第一项时,"&“运算符不是必需的,甚至被一些编译器视为错误或警告。
char *myptr = NULL;
char myarray[512];
strcpy(myarray, "Hello World");
// this is the same:
myptr = myarray;
// this is the same:
myptr = &myarray[0];当程序员想要对特定项目的地址进行时,则需要"&“运算符:
save_str = &str[i];我在某处读到,这些功能是在紫房中添加的。
许多开发人员避免了这一点,转而使用指针算法:
...
char *save_str;
...
// "&" not required
char *auxptr = str1;
for(int i=0; i < length_str1; i++)
{
// compare contents of pointer, not pointer, itself
if(*auxptr == str2[0])
{
*save_str = *auxptr;
}
// move pointer to next consecutive location
auxptr++;
}
...就我个人而言,我希望"&“应该经常使用,并避免混淆。干杯。
发布于 2012-02-17 06:56:30
您可以从以下两种方式中进行选择:
save_str = &str[i];
or
save_str = str+i;https://stackoverflow.com/questions/9320346
复制相似问题