首页 > 解决方案 > 如何编写指向函数?

问题描述

我在指针和函数部分遇到了一些问题。我被要求编写函数:char *mytoupper(char *p)将指向的字符串转换p为大写 then returns p

请注意,我无法使用这些<string.h>功能。这是我的做法吗?

#include <stdio.h>

char *mytoupper(char *p);

int main(int argc, char const *argv[]) {
    char str[100];
    printf("Please enter a string: ");
    scanf("%s", str);

    mytoupper(str);
    printf("The upercased string is: %s\n", str);
}

char mytoupper(char *p) {
    char result = *p;
    while (*p != '\0') {
        if ((*p >= 'a') && (*p <= 'z')) {
            *p = *p - 32;
        }
        p++;
    }
    return result;
}

请帮我检查一下。我只写了一个月的代码。我感谢所有的帮助。

标签: c

解决方案


在你的函数声明中

char *mytoupper(char *p);

你说它返回char *(指向char的指针)

在您的定义中,您说它char仅返回

char mytoupper(char *p)

这两个定义必须匹配,因此将其更改为

char *mytoupper(char *p)

然后在函数内部不存储第一个字符;存储指向第一个字符的指针并返回它。

char *result = p;
....
return result;

推荐阅读