关于指针:c:将 const char* 读入 sscanf 中的变量? | 珊瑚贝

c: reading const char* into a variable in sscanf?


我正在尝试将字符串/*char 扫描到变量中并将其传递给函数,但我收到错误 “format specifies type ‘char *’ but the argument has type ‘const char *'”。我需要 *info 成为一个 const char,但如果我改变它,我会得到其他错误。

如何将 const char *info 正确扫描到 sscanf() 中?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main(int argc, char** argv) {
    blk *block;
    char *line;
    const char *info;

    block = block_new();

    printf(“insert info”);

    while ( (line = readline()) != NULL) {
        sscanf(line,“%s”, info);
        insert(block, info);
        free(line);  
    }    
}

插入:insert(blk *block, const char *info)

当我更改为 char *info 而不是 const char 时,我收到错误:

1
2
3
4
5
warning: variable ‘info’ is uninitialized when used here
sscanf(line,“%s”, info);

note: initialize the variable ‘info’ to silence this warning
    char *info; = NULL

  • 除了删除 const 限定符以满足编译器的要求外,line 和 info 都是未初始化的变量。他们没有指出任何具体的事情。所以 sscanf(line,”%s”, info); 将无法做任何明智的事情,这是未定义的行为。
  • 为什么您”需要 *info 成为 const char”?
  • “我需要 *info 是一个 const char” – 不,你需要它是一个适当长的非 const 字符数组,或者一个指向适当大、动态分配的非 <x0 > 空间。无论是否动态分配,空间的内容都不能是const,因为你需要修改它们(通过sscanf)。
  • @WeatherVane *info 应该是一个 const char 因为函数 insert() 需要一个 const char 参数
  • 问题编辑后, info 仍然需要指向分配的内存。当 sscanf 取消引用 NULL 指针时,它将崩溃。
  • 为 const 参数提供非常量参数是可以接受的,但反之则不行。
  • @WeatherVane 好的!在不知道 info 有多大的情况下,我应该如何分配内存?
  • 这个问题太笼统了——这不是一个教程服务!您可以使用比您期望的任何输入更长的固定长度数组,例如 char info[1000]; 并使用 sscanf(line,”%999s”, info); 限制输入,或者您可以跟进关于 SO 的许多类似问题,例如如何读取未知长度的输入字符串?


你的代码和你想要的有一些问题。

const char* string; 声明了一个指向 char 的指针。你可以改变位置
你的指针指向的地方,你不能改变内存的内容
指针所指向的。

1
2
3
4
5
6
7
8
const char *string =“Hello”;
char line[] =“a b c”;

string =“World”; // legal
string[0] = ‘w’;  // illegal

string = line;    // legal
string[0] = ‘A’;  // illegal

所以使用 const char* 来读取带有 scanf 的输入


来源:https://www.codenong.com/48407719/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8625.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?