为什么c允许在没有声明的情况下初始化字符串? [英] why does c allow initialization of string without declaration?

查看:16
本文介绍了为什么c允许在没有声明的情况下初始化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 dyn_mat 的参数是常量时,代码运行没有任何错误,并且 s1 和 s2 确实存储了输入值.

When the arguments of dyn_mat are constants, the code runs through without any error and s1 and s2 do store the input values.

#include<stdio.h>

int main(int argc, char const *argv[])
{
    char *s1, *s2;
    int n1=7, n2=8;
    printf("Enter, %d 
", n1);

    scanf("%s", s1);
    scanf("%s", s2);

    int dyn_mat[155][347];

    return 0;
}

但是使用参数作为变量,比如 n1 和 n2,scanf 读取 s1 会导致分段错误.

but with arguments as variables, say n1 and n2, scanf reading s1 gives segmentation fault.

推荐答案

为什么 c 允许在不声明的情况下初始化字符串?

why does c allow initialization of string without declaration?

C中没有数据类型string.

在 C 中存储字符串的一种可能方法是使用字符数组,该数组的最后一个元素带有 0 以指示该字符串的结尾.

In C one possible way to store a string of characters is using an array of characters, with the last element of this array carring a 0 to indicate the end of this string.

您的程序没有声明任何数组,而只是指向字符的指针,这些字符没有分配您使用 scanf() 复制数据的内存.

You program does not declare any array, but just pointers to characters, which have no memory assigned to which you copy data using scanf().

你很幸运,第一次调用 scanf() 时程序没有崩溃.

Your just lucky the program does not crash with the first call to scanf().

这篇关于为什么c允许在没有声明的情况下初始化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆