Por que `&` não é permitido em C, mas em C ++ neste caso? Existe alguma divergência? [duplicado]
Nov 30 2020
Aqui está meu código C, eu uso void InitList(List &L);
No entanto, o buildlog do Code :: Blocks tem um erro:
esperado ';', ',' ou ')' antes do token '&'
#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;
}
Mas tentei em C ++, não há erro:
#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;
}
Respostas
2 Monstarules Dec 01 2020 at 02:09
Você não pode passar isso em uma declaração de função em C. Você precisa usar * se quiser fazer referência ao ponteiro para esses dados.
void InitList(List *L)
{
L->data = malloc(sizeof(ElementType)*MaxSize);
L->CurLength = 0;
}
E depois
List *L;
InitList (&L);
1 RemyLebeau Dec 01 2020 at 02:22
Em void InitList(List &L);
, L
está sendo passado por referência . C não oferece suporte a referências, que é um recurso C ++. Em C, você precisa passar L
por ponteiro (que é exatamente o que você main()
está tentando fazer ao usar List L; InitList(&L);
, mas a declaração de InitList()
está errada para isso), por exemplo:
#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;
}
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?
George Harrison ficou chateado por suas letras de 'Hurdy Gurdy Man' de Donovan não terem sido usadas