学习C:在函数之间传递字符串

时间:2018-10-02 17:33:01

标签: c

我很难在C中的函数之间传递字符串。这是代码中最简单的部分,其中包含以下错误:首先,用于转置的函数原型,它对字符串执行某些一元运算。我听说我们用char * str声明了字符串,所以这是正确的吗?

int main() {

    char *input;
    scanf("%s",&input);

    char *result;
    result = transpose(input);
    //[Error] 'transpose' cannot be used as a function

    printf("%s",result);
    return 0;

这是main()中转置函数的使用。我在以下注释中指出了哪些行会产生错误。

char *transpose(char *text) {
    char *T = text;
    return T;
}

最后是转置的函数定义:

// Notice that there is no expansion pattern used here
$path = '/var/www/import/2014047-0216/YukonGold.A2014047.1620.';
$re = '~\Q' . $path . '\E(?:[^.]+\.)?\w+$~';
$regexIterator = new RegexIterator(new GlobIterator("{$path}*"), $re);
foreach ($regexIterator as $filename) {
    echo $filename . "\n";
}

1 个答案:

答案 0 :(得分:1)

首先,您的代码存在问题

char *input; /* pointer variable should be initialized with valid memory */
scanf("%s",&input); /* this causes compiler warning, but seems you ignored ? */

input没有有效的内存,并且扫描未初始化的指针可能会导致崩溃。因此,您可以将input创建为

这样的char数组
char input[20]; 
scanf("%s",input); /* & is not required as input name itself address */

或者像下面这样为input动态分配内存

char *input = malloc(SIZE); /* define the SIZE value */
scanf("%s",input); 

示例代码

char *transpose(char *text) {
    char *T = text;
    return T;
}
int main(void) {
        char input[20];/* size of array you can define it, I just took 20 char */
        scanf("%s",input);
        char *result = transpose(input);
        printf("%s",result);
        return 0;
}

正如其他人在评论中建议的那样,最好使用fgets()而不是scanf()。对于例如

char input[20];
fgets(input,sizeof(input),stdin);
input[strcspn(input, "\n")] = 0; /* to remove the trailing \n if copied, use strcspn() */
相关问题