【问题标题】:How to pass array "by reference" in C? [duplicate]如何在C中“通过引用”传递数组? [复制]
【发布时间】:2017-05-16 14:02:37
【问题描述】:

这是我正在尝试做的,但我的代码要么没有编译,要么给我一个意外的输出“BC”而不是“B”。

#include <stdio.h>

void removeFirstAndLastChar(char** string) {
    *string += 1; // Removes the first character
    int i = 0;
    for (; *string[i] != '\0'; i++);
    *string[i - 1] = '\0';
}

int main(void) {
    char* title = "ABC";
    removeFirstAndLastChar(&title);
    printf("%s", title);
    // Expected output: B
    return 0;
}

我在这里查看了很多与通过引用传递指针有关的答案,但似乎没有一个包含我想在 removeFirstAndLastChar() 函数中执行的操作。

【问题讨论】:

  • 尝试修改字符串文字的未定义行为。
  • 你应该把char* title = "ABC";改成char title[] = "ABC";
  • 你需要(*string)[i] 而不是*string[i]
  • @Nidhoegger 使用指向文字的指针根本不正确,因为函数会修改它。

标签: c pointers pass-by-reference


【解决方案1】:

我不评判你的算法或C约定,评论你问题的朋友是完全正确的。但是如果你仍然这样做,你可以使用这种方法。

#include <stdio.h>
#include <string.h>

void removeFirstAndLastChar(char* string) {
    memmove(string,string+1,strlen(string));
    string[strlen(string)-1]=0;
}

int main(void) {
    char title[] = "ABC";
    removeFirstAndLastChar(title);
    printf("%s", title);
    // Expected output: B
    return 0;
}

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 2018-02-11
    • 2012-10-07
    • 2021-04-19
    • 2013-11-07
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多