代码之家  ›  专栏  ›  技术社区  ›  redsoxlost

在变量[closed]中存储字符串

c
  •  0
  • redsoxlost  · 技术社区  · 7 年前

    有人能解释一下如何将字符串(或字符数组)存储在长度较小的字符数组中吗?例如,以下面的例子。

    int main()
    {
       char ls_thread[10];
       sprintf(ls_thread,"Learning C is %s\n","fun");
       printf("%s",ls_thread);
       printf("Length of the string is %d",strlen(ls_thread));
       return 0; 
    }
    

    2 回复  |  直到 7 年前
        1
  •  2
  •   JJJ Sergey    7 年前

    您在代码中所做的是 无效写入

    想想记忆吧

    [-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-] ...
    |       reserved memory       |      non reserved memory     ...
    

    [L][e][a][r][n][i][n][g][ ][C][ ][i][s][ ][f][u][n][\n][\0][-] ...
    |       reserved memory       |      non reserved memory     ...
    

    在不属于你的记忆中写作会导致 未定义的行为 ,因为它可以作用于其他程序内存,甚至你的程序内存。


    你必须严格使用C语言,只使用你所要求的。

    当你使用 malloc ,使用 free ;那么一切都会好起来的。

        2
  •  2
  •   Sourav Ghosh    7 年前

    这是 undefined behavior

    正统剧 . 访问超出分配的内存是未定义的行为。

    在你的代码里, ls_thread char ,加上一个空终止符。试图进入第10个元素是一种冒险 无效 记忆,这导致了UB。