CC与CC++中&的区别与使用

在C语言中&表示取地址符;在C++中&引用;

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define OVERFLOW 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT10

typedef struct
{
  char *elem;
  int length;
  int listsize;
}SqList;

/* 线性表初始化*/
int InitList(SqList &L)
{
  L.elem=(char*)malloc(LIST_INIT_SIZE*sizeof(char));
  if(!L.elem)
    exit(OVERFLOW);
  L.length=0;
  L.listsize=0;
  return 0;
}

int main()
{  
  int y;
  SqList L;
  y=InintList(L);
  printf("y=%d",y);
  
  return 0;
}

这是因为C语言不支持&引用

解决办法;

1、将引用改为指针,然后在主函数中进行地址传送;


/* 线性表初始化*/
int InitList(SqList* L)
{
  L.elem=(char*)malloc(LIST_INIT_SIZE*sizeof(char));
  if(!L.elem)
    exit(OVERFLOW);
  L.length=0;
  L.listsize=0;
  return 0;
}
int main()
{  
  int y;
  SqList L;
  y=InintList(&L);
  printf("y=%d",y);
  
  return 0;
}

修改之后在此运行会出现,如下错误;

InitSeqlist.c:18:4: error: request for member ‘elem’ in something not a structure or union
   L.elem=(char*)malloc(LIST_INIT_SIZE*sizeof(char));
    ^
InitSeqlist.c:19:8: error: request for member ‘elem’ in something not a structure or union
   if(!L.elem)
        ^
InitSeqlist.c:21:4: error: request for member ‘length’ in something not a structure or union
   L.length=0;
    ^
InitSeqlist.c:22:4: error: request for member ‘listsize’ in something not a structure or union
   L.listsize=0;

在C语言中 . 与 -> 作用对象是不同的。

如果它是地址,就在它后边用 ->,如果它不是地址,就在它后边就用 .

/* 线性表初始化*/
int InitList(SqList *L)
{
  L->elem=(char*)malloc(LIST_INIT_SIZE*sizeof(char));
  if(!L->elem)
    exit(OVERFLOW);
  L->length=0;
  L->listsize=0;
  return 0;
}

例如:

#include <stdio.h>
#include <string.h>

typedef struct Person
{
  char name[20];
  int age;
}Per;

void test(Per* p)
{
  char* p = "Tom";
  memcpy(p->name, p, strlen(p));  //P是一个结构体指针,因此使用“结构体指针名->成员变量名”来引用变量
  p->age = 20;
}

int main()
{
  Per p;
  memset(p, 0, sizeof(Per));
  test(&tt);
  printf("Name:%s\n", p.name);    //p是个结构体变量,因此使用 “结构体名.成员变量” 来引用变量
  printf("Age:%d\n",p.age);
  return 0;
}
发布了84 篇原创文章 · 获赞 46 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/gufenchen/article/details/104170062
cc
今日推荐