ITeye博客

字符串赋值=和strcpy问题

JavaBlogs · 2014-05-04 11:13 · C++ · 编程语言 · C++ · strcpy · Markdown

#include<iostream>
#include<string.h>
using namespace std;

struct Student
{
    char name[10];
    int num;
    char sex;
};

int main()
{
    Student *p;
    p = new Student;
    strcpy(p->name, "Wang Fun");
   char chr[] = {"Wang Fun"};
  // p -> name =  {"Wang Fun"}; 错误,数组之间不能直接赋值
    p->num = 10123;
    p->sex = 'M';
    cout << p -> name << " " << p->num << " " << p -> sex <<endl;
    delete p;
    return 0;
}

 

  关于字符串的赋值问题,网上说得很多,都谈论的是,用‘=’号时是指向同一地址,strcopy时是得到两个相同的字符串,但是却没有提及到修改问题。

    其实,当用‘=’号赋值时,得到的字符串是不能够修改的,但是编译时却不会提示错误。而用strcpy复制时,可以对字符串修改,但在使用strcpy之前,应该用new或malloc等为字符串分配空间。

#include <iostream.h>
#include <string.h>
int main()

{

   char *str="hello";

   str[0]='H';

   cout<<endl<<str<<endl;

   return 0;
}

执行结果:

....关闭

 

#include <iostream.h>
#include <string.h>
int main()

{

   char *str;
   str=new char;
   strcpy(str,"hello");

   str[0]='H';

   cout<<endl<<str<<endl;

   return 0;
}

执行结果:

Hello

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。