如何在C中“通过引用”传递数组? [重复]

问题描述 投票:-9回答:1

这是我想要做的,但我的代码要么不编译或给我一个意外的输出“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()函数中执行的操作。

c pointers pass-by-reference
1个回答
2
投票

我不判断你的算法或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;
}
© www.soinside.com 2019 - 2024. All rights reserved.