2012-02-16 106 views
0

我目前正在从头开始编写strstr。在我的代码中,我编制了一个字符串的索引,并且最终我需要使用另一个指针保存字符串上的特定点。这里是我正在努力的代码部分:指向索引指针

char *save_str; 
for(int i=0;i<length_str1; i++) 
{ 
    if(str1[i]==str2[0]) 
    { 
     *save_str=str[i]; 

但是,它告诉我,我不能这样做。我怎样才能有一个指向特定字符的指针?

+0

编译器给出的错误信息是什么? – 2012-02-16 22:52:49

+0

这是一个功课练习吗? – 2012-02-16 22:53:57

+0

在处理这样的事情之前,你应该确保你理解指针和事物指针之间的区别。 '* save_str'在你的上下文中没有意义。 – 2012-02-16 23:06:52

回答

0

快速实用的答案

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]; 

我读的地方,即,加入这些功能,在purpouse。

许多开发人员避免这种情况,并使用指针算术,而是:

... 

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++; 
} 

... 

就个人而言,我希望,“&”应该是使用始终,并避免混淆。 干杯。

+0

非常有帮助..谢谢:) – 2012-02-17 01:37:41

1

您可以从以下两种方法可供选择:

save_str = &str[i]; 

or 

save_str = str+i;