Dlaczego `&` nie jest dozwolone w C, ale w C ++ w tym przypadku? Czy jest jakaś różnica? [duplikować]
Nov 30 2020
Oto mój kod w C, używam void InitList(List &L);
Jednak buildlog Code :: Blocks ma błąd:
oczekiwany „;”, „,” lub „)” przed tokenem „&”
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10
typedef int ElementType;
struct SeqList;
typedef struct SeqList List;
void InitList(List &L);
struct SeqList
{
ElementType *data;
int CurLength;
};
/*----------------------------------*/
void InitList(List &L)
{
(&L)->data = malloc(sizeof(ElementType)*MaxSize);
(&L)->CurLength = 0;
}
int main()
{
List L;
InitList(&L);
return 0;
}
Ale próbowałem w C ++, nie ma błędu:
#include <iostream>
using namespace std;
#define InitSize 100
typedef int ElementType;
struct SeqList;
typedef struct SeqList List;
void InitList(List &L);
struct SeqList
{
ElementType *data;
int CurLength;
};
/*----------------------------------*/
void InitList(List &L)
{
L.data = new ElementType[InitSize]; //L.data = malloc(...)
L.CurLength = 0;
}
int main()
{
List L;
InitList(L);
return 0;
}
Odpowiedzi
2 Monstarules Dec 01 2020 at 02:09
Nie możesz tego przekazać w deklaracji funkcji w C. Musisz użyć *, jeśli chcesz odwołać się do wskaźnika do tych danych.
void InitList(List *L)
{
L->data = malloc(sizeof(ElementType)*MaxSize);
L->CurLength = 0;
}
I wtedy
List *L;
InitList (&L);
1 RemyLebeau Dec 01 2020 at 02:22
W void InitList(List &L);
, L
jest przekazywany przez odniesienie . C nie obsługuje odwołań, to jest funkcja C ++. W C musisz L
zamiast tego przekazać wskaźnik (co jest dokładnie tym, co main()
próbujesz zrobić podczas używania List L; InitList(&L);
, ale deklaracja InitList()
jest niewłaściwa), np:
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10
typedef int ElementType;
struct SeqList;
typedef struct SeqList List;
void InitList(List *L);
void CleanupList(List *L);
struct SeqList
{
ElementType *data;
int CurLength;
};
/*----------------------------------*/
void InitList(List *L)
{
L->data = malloc(sizeof(ElementType)*MaxSize);
L->CurLength = 0;
}
void CleanupList(List *L)
{
free(L->data);
L->CurLength = 0;
}
int main()
{
List L;
InitList(&L);
...
CleanupList(&L);
return 0;
}