Updating a data array using pointers

How can I do for change the value of cars using pointers?
I tried the code below, but I cant use pointers with arrays... Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  #include<iostream>
#include<string>

using namespace std;


using namespace std;


struct data
{
 string car;
 string brand;
 
};


int main ()

{   
	int ncar;
    cout<<"Enter the number of cars";
	cin >> ncar;
    data *f= new data[ncar];
    size_t i;
        
   
   for(i=0;i<ncar;i++)
   { 
    cout<<"Observation "<<i+1<<": \n";
    cout<<"Enter with car"<<": \n";
    cin>> f[i].car; 
    cout<<"Enter with the brand"<<": \n";
    cin>> f[i].brand; 
    }
  
      	    
    
   
    data *f=&f[ncar]; // I think the problem is here because I cant using arrays with pointers... 
   (*f).car = newCar;
   
   
    for(i=0;i<ncar;i++)
	{
	  cout<<"Enter with correct car"<<": \n";
	   cin>> f[i].newcar; 
	} 
    
	
 	  
return 0;
}
 Put the code you need help with here.
Last edited on
Are you trying to create a new data with data *f=&f[ncar];?

A data * type is the same as data[] type when changing its values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main()
{
    int * i = new int[65];
    i[53]=5;
    int j[65];
    j[53]=5;
    cout<<i[53]<<" "<< j[53]<<endl; // this prints 5 two times
    delete [] i; //don't forget to free memory
    return 0;
}
Last edited on
data *f=&f[ncar];
First, you do introduce a pointer variable with name "f". However, you already have a pointer variable with name "f". Your compiler should say something about that.

Second. f[ncar] dereferences the pointer. It is equivalent to *(f+ncar). However, f points to a memory block that has only ncar data elements. You do dereference memory one past your array. If you want your new pointer to point to the beginning of the array, you can use f directly.
I want to create a function to change the value of the car.
Last edited on
You wouldn't need a function to change car or brand.

data[An element in the array goes here].car = "Whatever you want to change car to";
Last edited on
I need replace the values cars using pointers....
1
2
3
4
5
6
7
8
9
int * i = new int[5];
int * j = new int[5];

//You would need to give the ints inside i and j values before doing this

for(int a = 0; a<5; a++)
{
  i[a]=j[a];
}


You could do something like that.
Last edited on
Topic archived. No new replies allowed.