I'm trying to convert a c program to c++ basically a struct data type to a class but is keeps showing " 'first' was not declared in this scope". whereas c program is working just fine.
Original code
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
}*first=NULL;
void Display(struct Node *p)
{
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void Insert(struct Node *p,int index,int x)
{
struct Node *t;
int i;
if(index < 0 || index > 9)
return;
t=(struct Node *)malloc(sizeof(struct Node));
t->data=x;
if(index == 0)
{
t->next=first;
first=t;
}
else
{
for(i=0;i<index-1;i++)
p=p->next;
t->next=p->next;
p->next=t;
}
}
int main()
{
Insert(first,0,5);
Insert(first,1,10);
Insert(first,2,15);
Display(first);
return 0;
}
edited Code
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
void Display(struct Node *p){
while(p!=NULL){
std::cout << p->data << std::endl;
p=p->next;
}
}
void Insert(struct Node *p,int index,int x){
Node *t;
int i;
if(index < 0 || index > 9)
return;
t=new Node;
t->data=x;
if(index == 0){
t->next=first;
first=t;
}
else
{
for(i=0;i<index-1;i++)
p=p->next;
t->next=p->next;
p->next=t;
}
}
int main()
{
Node *first=NULL; //
Insert(first,1,10);
Insert(first,2,15);
Display(first);
return 0;
}
error is something related to "Node *first = Null" line something to do with global pointer Insert(first,0,5);
In the C program you declared variable first
in the file scope.
struct Node
{
int data;
struct Node *next;
}*first=NULL;
So it is visible in all functions defined after the structure definition.
In the C++ program you declared the variable first
in a block scope of main
int main()
{
Node *first=NULL;
//...
So it is invisible inside the function Insert
in this code snippet
if(index == 0){
t->next=first;
first=t;
}
In any case the function Insert
is invalid because at least there is no check whether p
is equal to nullptr
in this for loop
for(i=0;i<index-1;i++)
p=p->next;
that can result in undefined behavior.
The first function parameter should have a referenced type as for example
void Insert(struct Node * &p,int index,int x){
In this case you could write for example
if(index == 0){
t->next=p;
p=t;
}
and the pointer first defined in main will be changed.
And if you want to rewrite the list in C++ then the provided functions should be declared as member functions of the class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.