I am having problems with accessing individual structure elemnsts. How to output each structure element using pointer?
#include <iostream>
using namespace std;
struct student{
int rollno;
float marks;
char name[45];
};
int main(){
student s1[2]={{1,50.23,"abc"},{2,65.54,"def"}};
for(int j=0;j<2;j++){
cout<<"Output Rollno, Marks and Name Using Pointer"
}
return 0;
}
Just assign the address to a pointer, and print it.
student *ptr=s1; // or &s1[0], instead.
cout<<ptr->rollno;
You don't have a pointer.
To output the fields, you do what you'd do in any other situation, e.g.:
cout << "marks = " << s1[j] << "\n";
your loop should be something like:
for(int j=0;j<2;j++){
cout<<"Rollno:" << s1[j].rollno << " Marks:" << s1[j].marks << " Name:" << s1[j].name << endl;
}
or, using pointer (i.e. array + offset):
for(int j=0;j<2;j++){
cout<<"Rollno:" << (s1+j)->rollno << " Marks:" << (s1+j)->marks << " Name:" << (s1+j)->name << endl;
}
If you wanted to be real raw:
void* ptr = &s1[0];
for(int j=0;j<2;j++){
cout<< (int)*ptr << "," << (float)*(ptr+sizeof(int)) << "," << (char*)*(ptr+sizeof(int)+sizeof(float)) << endl;
}
char* p = (char* )s1;
for(int j=0;j<2;j++){
int* a = (int*) p;
cout << *a << " ";
a++;
float* b = (float*) a;
cout << *b << " ";
b++;
char* c = (char*) b;
cout << c << " ";
c = c + 45 + strlen(c);
cout<<endl;
p = c;
}
Related
#include <iostream>
#include "student.h"
using namespace std;
int main()
{
// inputting the number of students
int n;
cout << "How many students would you like to process?" << endl;
cin >> n;
student* s[n];
string tmp;
double t;
// entering each student details
for (int i = 0; i < n; i++)
{
// dynamically allocating object
s[i] = new student();
cout << "Enter first name for student " << (i + 1) << endl;
cin >> tmp;
s[i]->setFirstName(tmp);
cout << "Enter middle name for student " << (i + 1) << endl;
cin >> tmp;
s[i]->setMiddleName(tmp);
cout << "Enter last name for student " << (i + 1) << endl;
cin >> tmp;
s[i]->setLastName(tmp);
cout << "Enter GPA for student " << (i + 1) << endl;
cin >> t;
s[i]->setGPA(t);
}
double avgGPA = 0;
// printing the student details
cout << "Students:" << endl;
cout << "---------" << endl
<< endl;
for (int i = 0; i < n; i++)
{
cout << s[i]->getFirstName() << " " << s[i]->getMiddleName() << " " << s[i]->getLastName() << " " << s[i]->getGPA() << endl;
avgGPA += s[i]->getGPA();
}
avgGPA /= n;
// printing the average GPA
cout << endl
<< "Average GPA: " << avgGPA;
// freeing the memory allocated to objects
for (int i = 0; i < n; i++)
delete s[i];
return 0;
}
Under the main function student * s [n]; says the array type is not assignable to the line.It also gives an error that the expression must contain a literal. I thought I was doing everything right, but there was an error. What is the solution to this error can anyone help?
student* s[n]; is a Variable-Length Array (VLA), which is not in the standard C++.
You should use std::vector like std::vector<student*> s(n);.
Also add #include <vector> at the beginning of your code to use that.
i have some trouble in dynamic allocation with 'new' and reference. Please see a simple code below.
#include<iostream>
using namespace std;
void allocer(int *pt, int *pt2);
int main()
{
int num = 3;
int num2 = 7;
int *pt=#
int *pt2 = &num2;
allocer(pt, pt2);
cout << "1. *pt= " << *pt << " *pt2= " << *pt2 << endl;
cout << "2. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
}
void allocer(int *pt, int *pt2)
{
int temp;
temp = *pt;
pt = new int[2];
pt[0] = *pt2;
pt[1] = temp;
cout << "3. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
}
What i want to do is to make the function 'allocer' get 2 arguments which are the int pointer and allocate memory on one of them. As you can see, *pt becomes an array to take 2 integers. Inside of the function it works well which means the sentence that i marked 3. printed as what i intended. However, 1, 2 doesn't work. 1 prints the original datas(*pt= 3, *pt2= 7), 2 prints error(*pt= 3, *pt2= -81203841).
How to solve it?
You are passing in the pt and pt2 variables by value, so any new values that allocer assigns to them is kept local to allocer only and not reflected back to main.
To do what you are attempting, you need to pass pt by reference (int* &pt) or by pointer (int** pt) so that allocer can modify the variable in main that is being referred to.
Also, there is no good reason to pass pt2 as a pointer at all since allocer doesn't use it as a pointer, it only dereferences pt2 to get at the actual int, so you should just pass in the actual int by value instead.
Try something more like this:
#include <iostream>
using namespace std;
void allocer(int* &pt, int i2);
int main()
{
int num = 3;
int num2 = 7;
int *pt = #
int *pt2 = &num2;
allocer(pt, *pt2);
cout << "1. *pt= " << *pt << " *pt2= " << *pt2 << endl;
cout << "2. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
delete[] pt;
return 0;
}
void allocer(int* &pt, int i2)
{
int temp = *pt;
pt = new int[2];
pt[0] = i2;
pt[1] = temp;
cout << "3. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
}
Or
#include <iostream>
using namespace std;
void allocer(int** pt, int i2);
int main()
{
int num = 3;
int num2 = 7;
int *pt = #
int *pt2 = &num2;
allocer(&pt, *pt2);
cout << "1. *pt= " << *pt << " *pt2= " << *pt2 << endl;
cout << "2. pt[0]= " << pt[0] << " pt[1]= " << pt[1] << endl;
delete[] pt;
return 0;
}
void allocer(int** pt, int i2)
{
int temp = **pt;
*pt = new int[2];
(*pt)[0] = i2;
(*pt)[1] = temp;
cout << "3. pt[0]= " << (*pt)[0] << " pt[1]= " << (*pt)[1] << endl;
}
What you just did was that you dynamically allocated the pt that is inside the function. And this function variable pt is local and is not the same as the pt in the main function.
What you can do is, that you can pass the address of the pointer itself if you want to dynamically allocate memory to that pointer.
I'm trying to print the value of pointer array using for loop as usual, and I managed to print value stored in one object, but can't print the value stored in another object. My classes are defined in Predmet.h:
#include <iostream>
#include <string>
using namespace std;
class Predmet
{
public:
int numberOfItems;
string name;
Predmet();
~Predmet();
};
and Plaza.h:
class Plaza
{
public:
int length;
double x;
double y;
Plaza();
~Plaza();
};
My main.cpp looks like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include "Plaza.h"
#include "Predmet.h"
using namespace std;
int main() {
int n, m;
int *numberOfBeaches;
Plaza *obj1;
Predmet *obj2;
cout << "Enter number of beaches (N): ";
cin >> n;
obj1 = new Plaza[n];
for (int i = 0; i < n; i++) {
cout << "Enter length and coordinates for " << i + 1 << ". beach: " << endl;
cin >> obj1[i].length;
cin >> obj1[i].x >> obj1[i].y;
}
cout << endl;
cout << "Enter number of items (M): ";
cin >> m;
obj2 = new Predmet[m];
numberOfBeaches = new int[n];
for (int i = 0; i < m; i++) {
cout << "Enter ordinal number of beach for " << i + 1 << ". item: ";
cin >> numberOfBeaches[i];
cout << "Enter how much of item you have and name of the item: ";
cin >> obj2[i].numberOfItems >> obj2[i].name;
}
int *p;
for (int i = 0; i < n; i++) {
p = find(numberOfBeaches, numberOfBeaches + n, i + 1);
if (*p == i + 1) {
for (int j = 0; j < m; j++) {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << obj2[j].numberOfItems << " " << obj2[j].name << endl;
}
}
else {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].length << " - predmeti: " << endl;
}
}
delete[] obj1;
delete[] obj2;
delete[] numberOfBeaches;
system("pause");
return 0;
}
Everything was working until this point where I add printing for obj2[i].kolicina and obj2[i].opis, I get weird looking result as a print and this exception thrown, as you can see below:
What am I doing wrong? Thanks in advance.
EDIT:
After suggestions in the comments, I managed to fix the code (updated version above) to print it proper way, only when I have M > 1 (e.g. M = 2) I get duplicate printing of lines? How can I fix that?
The problem is with this line:
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " D=" << obj1[i].duljina << " - predmeti: " << obj2[i].kolicina << " " << obj2[i].opis << endl;
obj2 is being defined as having m elements, yet you are using i, which has the values 0 <= i < n. I don't know what m's relation is to n, but that is certainly where you should start.
obj2contains melements:
obj2 = new Predmet[m];
brojPlaze contains n elements:
brojPlaze = new int[n];
you are looping over all Predmet in obj2:
for (int i = 0; i < m; i++) {
...
}
and inside the loop, you access element i of brojPlaze:
cin >> brojPlaze[i];
but i goes from 0 to m, and m can be greater than the n element brojPlaze contains. thus, you may access an element outside of the array, which can cause a lot of undesired effects...
In CPP file #1, I'm trying to loop through the array to see if any of the inputed names match Mordor or the_Vale (from CPP file #2 towards the bottom), however my loop is not working and I only know how to loop through a string array, not a char
#Header File#
#ifndef KINGDOM_H
#define KINGDOM_H
namespace westeros
{
class Kingdom
{
public: //Makes this class public to the rest of the code
char m_name[32];
int m_population;
int count = 0;
};
void display(Kingdom&);
void display(Kingdom* k, int x);
void display(Kingdom* k, int x, int z);
void display(Kingdom* k, int x, char foo[]);
}
#endif
#CPP FIle #1#
#include <iostream>
#include "kingdom.h"
void display(Kingdom* k, int x, char foo[])
{
int a = 0;
int found = 0;
cout << "Searching for kingdom " << foo << " in Westeros" << endl;
for (a; a < x; a++)
{
if (k[a].m_name == foo)
//(strcmp(k[a].m_name) == 0)//Not working
{
cout << k[a].m_name << ", population " << k[a].m_population << endl;
found = 1;
}
}
if (found == 0)
{
cout << foo << " is not part of Westeros." << endl;
}
}
}
## CPP File (main) #2##
#include <iostream>
#include "kingdom.h"
using namespace std;
using namespace westeros;
int main(void)
{
int count = 0; // the number of kingdoms in the array
// TODO: declare the kingdoms pointer here (don't forget to initialize it)
Kingdom* pKingdoms = nullptr;
cout << "==========" << endl
<< "Input data" << endl
<< "==========" << endl
<< "Enter the number of kingdoms: ";
cin >> count;
cin.ignore();
pKingdoms = new Kingdom[count];
for (int i = 0; i < count; ++i)
{
// TODO: add code to accept user input for the kingdoms array
int x = 0;
x++;
cout << "Enter the name for kingdom #" << x + i << ": ";
cin >> pKingdoms[i].m_name;
cout << "Enter the number people living in " << pKingdoms[i].m_name << ": ";
cin >> pKingdoms[i].m_population;
}
cout << "==========" << endl << endl;
// testing that "display(...)" works
cout << "------------------------------" << endl
<< "The first kingdom of Westeros" << endl
<< "------------------------------" << endl;
display(pKingdoms[0]);
cout << "------------------------------" << endl << endl;
// This is where I am having the problem
display(pKingdoms, count, "Mordor");
cout << endl;
display(pKingdoms, count, "The_Vale");
cout << endl;
cout << endl;
delete[] pKingdoms;
pKingdoms = nullptr;
return 0;
}
if (k[a].m_name == foo)
This is not how you compare two C-Style strings. This only compares the pointers, which should result in false almost certainly. You could use strcmp (#include <string.h>):
if (!strcmp(k[a].m_name, foo))
A better way, though, since you're programming in C++, use std::string:
std::string m_name;
and the comparison would have worked flawlessly.
The code that I posted below is supposed to work in recursion (the Sort() function) even up to 1kk times. The problem is: when the Sort() function gets into loop number 43385 the console stops working and alerts: "The program has stopped working". Is it a problem with memory? If yes, where is the bad part of the code? Greetings.
#include <iostream>
#include <string>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
if(i==n-1)
return counter;
else
Sort(i+1);
}
int main()
{
cin >> n >> a >> b;
Sort(0);
return 0;
}
Perhaps a call stack overflow because of too deep recursion?
To add to iltal's comment, you may want to print out information on strings a, b: a.size(), a.length(), a.capacity(), a.max_size()
I'm not sure what this code is trying to do. Here's a revision, with some print statements added, along with a random string generator.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
cout << "x = " << x << " set tmp0 to " << tmp0 << " and tmp1 to " << tmp1 << endl;
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
cout << " endof sort: a is " << a << endl;
cout << " b is " << b << endl;
if(i==n-1) {
cout << "Returning counter " << counter << endl;
return counter;
} else {
cout << "Running sort(" << i << " + 1)" << endl;
Sort(i+1);
}
}
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
int main()
{
n = 50;
srand(time(NULL));
string a0, b0;
a0 = randomStrGen(n);
a = a0;
b0 = randomStrGen(n);
b = b0;
// cin >> n >> a >> b;
cout << "Max string size is " << a.max_size() << endl;
cout << "Calling sort" << endl
<< " n is " << n << endl
<< " a is " << a << endl
<< " b is " << b << endl;
Sort(0);
cout << " endof program: a inital: " << a0 << endl;
cout << " a final: " << a << endl;
cout << " b inital: " << b0 << endl;
cout << " b final: " << b << endl;
return 0;
}
counter is of type int but it has a lot of values summed in it which may be in all larger than int. maybe try int64?
You could hard code some test cases, like n = 20, a = "xyz...", b = "abc...", and add print statements to your sort function to track what is going on. Also, it may be helpful to add some comments to clarify what the purpose of the different loops are.