zoukankan      html  css  js  c++  java
  • 字符串必须申请内存空间

    #include "stdafx.h"
    #include "stdlib.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //输入字符串 
        char *str; 
        scanf("%s",str); 
        printf("输出输入的字符串*str=%s
    ",&str); 
        system("pause");
        return 0;
    }

    代码出现指针问题

    原因:

    这样使用容易造成内存错误。
    char *str; 声明了一个指针,但没有对其进行初始化,他的值是一个无法预知的值。可能指向一段空的内存,也可能指向其他程序使用的内存地址,也可能不是无用的内存地址。
    scanf("%s",str); 的意思是获取一段字符串,并把字符串放到str所指的内存地址之后的一段空间。但本程序并没有申请内存空间,所指的那段内存空间就是上面三种情况中的一种。所以有可能就将其他程序的内存内容给改变了,其他程序崩溃了。
    printf("输出输入的字符串*str=%s ",&str);
    这个输出语句也存在问题,&str 应改为str,这的值是字符串地址的头指针,而不是str这个变量所在的地址。&str str这个变量在内存中的地址。str 的值是字符串地址的头指针

    改正:

    #include "stdafx.h"
    #include "stdlib.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //输入字符串 
        char str[50];
        scanf("%s",str);
        printf("输出输入的字符串*str=%s
    ",str);
        system("pause");
        return 0;
    }

    或者:

    #include "stdafx.h"
    #include "stdlib.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //输入字符串 
        char *str = (char*)malloc(100);
        scanf("%s",str);
        printf("输出输入的字符串*str=%s
    ",str);
        system("pause");
        return 0;
    }
  • 相关阅读:
    [hdu2196]Computer树的直径
    [poj2342]Anniversary party树形dp入门
    链式前向星模板
    LintCode-50.数组剔除元素后的乘积
    Markdown的基本语法
    LintCode-8.旋转字符串
    LintCode-1.A + B 问题
    LintCode-61.搜索区间
    LintCode-88.最近公共祖先
    LintCode-54.转换字符串到整数
  • 原文地址:https://www.cnblogs.com/mhq-martin/p/11427407.html
Copyright © 2011-2022 走看看