为什么C允许字符串初始化没有申报? [英] why does c allow initialization of string without declaration?

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

问题描述

在dyn_mat的参数是常数,在code纵贯没有任何错误和S1和S2做存储输入值。

 #包括LT&;&stdio.h中GT;INT主(INT ARGC,字符常量*的argv [])
{
    字符* S1,S2 *;
    INT N1 = 7,N2 = 8;
    的printf(请输入%D \\ n,N1);    scanf函数(%S,S1);
    scanf的(%S,S2);    INT dyn_mat [155] [347];    返回0;
}

但参数变量,说n1和n2,scanf函数读取S1给人分段错误。


解决方案

  

为什么C允许字符串初始化不申报?


有没有数据类型字符串在C

在C到存储字符的字符串的一种可能的方法是使用一个字符数组,与该阵列carring一个 0 来表示的这个端部的最后一个元素字符串。

您程序不声明任何数组,只是指向字符,其中有没有记忆分配给您复制使用数据 scanf()的

您只是运气好节目不会在第一次调用 scanf()的

崩溃

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 \n", n1);

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

    int dyn_mat[155][347];

    return 0;
}

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

解决方案

why does c allow initialization of string without declaration?

There is no data type string in C.

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.

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

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

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

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