【问题标题】:Problems with C pointersC 指针的问题
【发布时间】:2015-04-08 15:24:40
【问题描述】:

所以我一直无法理解 C 中的指针。我的问题是如何让 char * find_ch_ptr 返回一个 char*。我也一直在到处遇到演员问题。如果这里有什么问题,请您详细解释一下吗?

/*
 * Return a pointer to the first occurrence of <ch> in <string>,
 * or NULL if the <ch> is not in <string>.
 *****
 * YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING.
 *****
 */
char *find_ch_ptr(char *string, char ch) {
        char * point = (char*)(string + 0);
        char * c = &ch;
        while(point != '\0') {
                if(point == c) return (char*)point;
                else *point++;
        }
        return (char*)point;    // placeholder
}

【问题讨论】:

  • 您不需要将char* 转换为char*
  • 你不需要任何演员表,else *point++ 也可以,就像else point++; 一样
  • 你不是说*point++ 你是说point++
  • @pm100;效果是一样的。
  • 感谢大家的帮助!

标签: c pointers char


【解决方案1】:
while(point != '\0') 

应该是

while(*point != '\0') 

有些地方你需要取消引用指针而你没有这样做。喜欢

while(*point != '\0')
{
  if(*point == ch)
  return point;
  else
  point ++;
}

PS:point 是一个指向某个有效内存位置的指针,存储在该位置的值是通过取消引用 *point 获得的

【讨论】:

  • @Gopi;我的错!他当然可以返回passes字符串的元素地址。
  • 感谢您的帮助!
【解决方案2】:

要比较point 当前指向的字符,您需要像这样使用* 运算符取消对point 的引用

while (*point != '\0')

然后你想比较你正在搜索的角色,但你也做错了。

您正在将变量ch 的地址与当前point 指向的地址进行比较,这是您需要的错误

if (*point == ch)

改为。

【讨论】:

  • 感谢您的帮助!
【解决方案3】:

尝试类似strchr()

用法:

#include <string.h>
ptr = strchr( s, c );

【讨论】:

  • 可能是作业,他们必须编写自己的函数。
  • @iharob 特别是考虑到评论YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING.
【解决方案4】:

这是您的代码的工作版本

请告诉老师你是从堆栈溢出中得到的

char *find_ch_ptr(char *string, char ch) {

        while(*string != '\0') {
                if(*string == ch) 
                   return string;
                else string++;
        }
        return (char*)0;
}

或 K&R 方式

while(*string && *string!=ch);
return str;

【讨论】:

  • 谢谢!虽然已经从上面的 cmets 修复了它。会做
【解决方案5】:

在检查等价 '\0' 之前需要取消对 while 循环条件的引用。

不需要c变量,可以直接使用ch参数在while循环内进行检查。

这是一个工作示例:

#include<stdio.h>

char *find_ch_ptr(char *string, char ch) {
    char *point = string;
    while(*point != '\0') {
            if(*point == ch)
            {
                    return point;
            }
            else
            {
                    point++;
            }
    }
    return point;    // placeholder
}

int main(int argc, char* argv[]){
    printf("%c\n", *find_ch_ptr("hello world", 'r'));
    return 0;
}

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 2011-08-02
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多