C - 在函数中写入字符串。错误 :expected expression

标签 c string function pointers

我正在尝试编写一个函数,从一个字符串中提取几个字符并将其分配给另一个字符串。

代码:

// Problem 10.4
// String extraction function

#include <stdio.h>

void substring (char source[], int start, int count, char result[])
{
    int i;

    for (i = 0; i <= count; ++i) {
        result[i] = source[start];
    }

    result[i+1] = '\0';
}

int main (void)
{
    void substring (char source[], int start, int count, char result[]);
    char source[] = "character", result[80];
    int start, count;

    substring(source[], 4, 3, result[]);

    printf("%s\n", result);

    return 0;

}

Xcode 告诉我该行

substring(source[], 4, 3, result[]);

是“期待一个表达式”,它不会让我编译。

我很困惑,因为我的函数没有返回任何值(它在自身内部进行字符串赋值,因为它是一个字符串,这是否意味着指针被传递给了函数?在这种情况下不是吗?意味着字符串本身正在被修改而不是本地副本?如果原始字符串正在被修改,那么为什么我必须返回一个值?)

我不完全确定问题出在哪里,尽管我怀疑这与我没有在句法上将指针传递给我的函数有关。

提前感谢您提供的任何见解。

最佳答案

这不是将数组传递给函数的方式。

您正在使用 source[],不需要此 '[]'。

数组在 C 中作为引用传递。当您传递一个数组 source[] (fun(source)) 时,它的基地址将被传递到函数中,就像指针的情况一样。

substring(source, 4, 3, result);

此外,您的代码通过调用上述调用产生“aaaa”。您需要在循环中递增 start 变量,如果您的意思是 start=4,请不要忘记索引从 0 开始,它从第 5 个字符“a”开始并导致“acte”。

代码:

    // Problem 10.4
// String extraction function

#include <stdio.h>

void substring (char source[], int start, int count, char result[])
{
    int i;

    for (i = 0; i <= count; ++i) {
        result[i] = source[start++];
    }

    result[i+1] = '\0';
}

int main (void)
{
    void substring (char source[], int start, int count, char result[]);
    char source[] = "character", result[80];
    int start, count;

    substring(source, 4, 3, result);

    printf("%s\n", result);

    return 0;

}

一切顺利...

关于C - 在函数中写入字符串。错误 :expected expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751082/

相关文章:

c - 使用 libpng 在 C 中以灰度或 RGB 编写 PNG

c - 大型与嵌套状态机

html - 在不破坏 HTML 标签的情况下切割 HTML 字符串

iPhone 格式化字符串

r - 计算 r 中数据函数的导数

c - 在C中,取消任务最基本的方法是什么?

c++ - 试图通过 system() 运行字符串命令

angularjs - Angular,尝试使用服务时出现 "x is not a function"

c - 函数调用的参数不匹配

c - 创建 C 货币计算器时遇到一些问题