c - 从函数传递 scanf 字符串

标签 c

It shows nothing when you pass the string to the function

int main(void){
    char *string[200];
    getChar(string);//starts function
    printf("This is the string %s",*string);//prints
    return 0;
}

Void getChar(char *String[200]){
    scanf(" %s",String[200]);//gets string
}

最佳答案

存在多个问题:

  • 您应该使用 char 数组而不是 char * 数组,
  • 您应该将数组直接传递给 scanf():
  • Void 没有大写:void
  • getChar 难以读取字符串,应在使用前声明或定义。
  • scanf("%s", 中的初始空格是多余的:%s 已经跳过了初始空格。
  • 您必须告诉 scanf() 要存储到目标数组中的最大字符数,否则如果输入的字符太多,您将出现未定义的行为。

修改后的版本:

#include <stdio.h>

int getword200(char *buf) {
    return scanf("%199s", buf);
} 

int main() {
    char word[200];
    if (getword200(word) == 1)
        printf("This is the string: %s\n", word);
    return 0;
}

上述函数假定数组的长度至少为 200。传递实际数组长度并修改代码以处理任何长度会更通用:

#include <limits.h>
#include <stdio.h>

int getword(char *buf, size_t size) {
    char format[32];
    int length;
    if (size == 0)
        return NULL;
    if (size == 1) {
        *buf = '\0';
        return buf;
    }
    if (size > INT_MAX)
        length = INT_MAX;
    else
        length = size - 1;
    snprintf(format, sizeof format, "%%%ds", length)
    return scanf(format, buf);
}

int main() {
    char word[200];
    if (getword(word, sizeof word) == 1)
        printf("This is the string: %s\n", word);
    return 0;
}

关于c - 从函数传递 scanf 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66633245/

相关文章:

计算快速对数基数 2 上限

c - 为什么验证方法不能正常工作?

c - 寻找一种在 C 中调用具有不同参数的函数的方法

c - 为什么这段代码会导致死锁? (生产者消费者模型)

c - C 中的字节顺序宏

c - 多重定义 ... 链接器错误

计数 C 指令

c - #include <文件名> 和 #include "filename"之间的区别

c++ - 如何判断数组100的个数不相等

java - 来自指针的 JNA Java 结构