【C语言】使用结构体和malloc函数时的一些错误。

使用结构体错误:


#include <stdio.h>
struct STU
{
    char *name;
    int score;
}stu,*pstu;
int main ()
{
    strcpy(stu.name,"bit-tech");
    strcpy(pstu->name,"bit-tech");
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

错误一:strcpy(stu.name,”bit-tech”);

结构体中的成员name是一个指针,声明结构体时并没有对结构体成员初始化,所以成员name没有指向指定的空间,当我们在主函数中想向通过strcpy函数对成员name指向的空间拷贝内容时,却发现程序挂掉了。


错误二:strcpy(pstu->name,”bit-tech”);

首先也存在错误一所指的一点错误! 
其次*pstu是一个结构体指针,我们在主函数中并没有将pstu指向我们的结构体对象stu,也就是没有指向我们声明的结构体,当你想通过pstu->name时,你会发现程序依然会挂掉,因为pstu不能访问成员name。


使用malloc函数错误:


#include <stdio.h>
int Getmemory(char *q)
{
    q = (char *)mallo(10*sizeof(char));
    return q;
}
int main ()
{
    char *p = NULL;
    Getmemory(p);
    strcpy(p,"bit-tech");
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

错误一:Getmemory(p);

传送的实参是一级指针,当我们调用Getmemory函数时,形参应该用二级指针来接收。


错误二:Getmemory函数定义

我们想在Getmemory函数里开辟想要的空间,然后在主函数中使用,可是我们发现调用Getmemory函数结束后,分配的空间也不为主函数使用。因为传参时,只是将Getmemory函数的实参做一份拷贝传给形参q。

猜你喜欢

转载自blog.csdn.net/zjy900507/article/details/80623413