簡體   English   中英

我如何將字符串(作為用戶輸入)傳遞給 c 中的 function?

[英]how can i pass string(taken as input from user) to a function in c?

#include<stdio.h>
void add(int a,int b)
{
    int c=a+b;
    printf("\nSum=%d",c);
}
void hello(char *name)
{
    printf("Hello %s",*name);
}
int main()
{
    int  a,b;
    char name[20];
    void (*ptr)(int,int)=&add;
    void (*hello)(char*)=hello;
    printf("Enter your Name:");
    scanf("%s",&name);
    hello(&name);
    printf("Enter the two values\n");
    scanf("%d%d",&a,&b);
    ptr(a,b);
    return 0;
}

我想從用戶那里獲取輸入,然后將其傳遞給 function 但我無法這樣做。

這是我的編譯器顯示為錯誤的內容: https://i.stack.imgur.com/DVYL6.png

您不需要訪問數組地址,當您將它傳遞給函數時,它將被隱式轉換為char* (包括scanfhello )。

我沒有看到函數指針的使用,所以為了簡化代碼,我會這樣重寫它:

#include <stdio.h>

void add(int a, int b)
{
    printf("Sum = %d\n", a + b);
}

void hello(char *name)
{
    printf("Hello %s\n", name);
}

int main()
{
    int a = 0, b = 0;
    char name[20];

    printf("Enter your Name:\n");
    scanf("%s", name);
    hello(name);

    printf("Enter the two values\n");
    scanf("%d%d", &a ,&b);
    add(a, b);
    
    return 0;
}

如果你堅持使用指針,那么 main 應該這樣寫:

int main()
{
    int  a = 0, b = 0;
    char name[20];

    void (*add_ptr)(int, int) = &add;
    void (*hello_ptr)(char *) = &hello;

    printf("Enter your Name:\n");
    scanf("%s", name);
    hello_ptr(name);

    printf("Enter the two values\n");
    scanf("%d%d", &a, &b);
    add_ptr(a, b);

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM