c - 将字符串引用传递给函数

标签 c string

<分区>

在我下面的代码中:

#include <stdio.h>
#include <stdlib.h>

void build(char *input){



// how do I get the first string "one" here from the *input pointer? and dissect the string - 'one' so that I can get each character separately 
}
int main() {
    const char *strings[] = { "one", "two", "three" };
    printf("1st string is %s\n", strings[0]);
    build(strings);
    return 0;
}

我的这个程序的目标是在我的构建函数中获取每个字符串,比如“一个”,并分离出每个字符 - 'o'、'n'、'e',然后找到一个数字,它是总和111('o') + 110('n') + 101 ('e') = 322 的 ASCII 码。(每个字符串可能有不同的长度)

After compiling others answer I came up with this: Please let me know if this ok?


Possible Answer:

#include <stdio.h>
#include <stdlib.h>

void build(char *input) {

    int i = 0;
    int a=0
    while (*input != '\0') {
        printf("character is %c\n", *input);
        a=a+*input;
        input++;
    }
printf("sum of ascii value of each character is %d\n",a);
    printf("------\n");

}

int main() {

    const char *strings[] = { "one", "two", "three" };

    int i = 0;
    for (i = 0; i < sizeof strings / sizeof *strings; i++)
        build(strings[i]);

    return 0;
}

最佳答案

strings 实际上是一个指向字符的指针。所以用 strings 参数调用 build() 是非常错误的。

这里有很多错误:

  1. 作为一个指针到指针到字符的指针,您需要两个解引用操作来访问字符。 *strings[0](和string[0][0],以及**strings)是第一个字符串的第一个字符。

  2. build() 函数需要一个指向 char 的指针。如果您计划向 build() 传递一个字符串,这很好,这听起来像您想要的。或许?但是在构建函数中,您试图打印指针的值。但如果这就是您想要的,那也没关系。

将字符串从数组传递给函数很简单! 你这样做:

build(strings[0]);

数组索引提供一级解引用,所以 build() 仍然得到一个 char *。在 build() 中,您可以非常简单地访问字符串的每个字符,例如 *input 或 input[0]。

而且您绝对可以在处理字符串时尽快计算长度。 build() 不必计算传递给它的字符串的长度。

关于c - 将字符串引用传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531489/

相关文章:

c - 为什么我会收到段错误?

将结构复制到另一个

python - 命令行 Python 应用程序中的多行用户输入

c++ - 从 vector 中删除空元素

javascript - 从 Javascript 中的字符串获取 URL 值

java - Mapstruct 映射 boolean 值到字符串

c - Xcode 返回 (lldb),同时运行 C 应用程序

c++ - 是否有任何 LAME C++ 包装器\简化器(在 Linux Mac 和纯代码 Win 上工作)?

c - 将 int 数组打印为字符串

c - 将文件中的行保存到新字符串中。 C