How to initialize dynamicly array from struct C++ - c++

I have an assignment to write a function that dynamicly initialize an array from struct that is in the header file. and for some resone I am keep getting the same error "uninitialized local variable 'columnData' used
this is the header file
#ifndef QUEUE_H
#define QUEUE_H
/* a queue contains positive integer values. */
typedef struct queue
{
int arraySize;
int* column;
} queue;
void initQueue(queue* q, unsigned int size);
void cleanQueue(queue* q);
void enqueue(queue* q, unsigned int newValue);
int dequeue(queue* q); // return element in top of queue, or -1 if empty
#endif /* QUEUE_H */
this is my code:
#include <iostream>
#include "queue.h"
int main()
{
queue* columnData;
unsigned int size = 0;
std::cout << "Please enter column size: ";
std::cin >> size;
initQueue(columnData, size);
printf("%d", &columnData->column[0]);
}
void initQueue(queue* q, unsigned int size) {
q->column = new int[size];
q->column[0] = 5;
}
void cleanQueue(queue* q) {
}
void enqueue(queue* q, unsigned int newValue) {
}
int dequeue(queue* q) {
return 1;
}
If someone can help me it will be great.

You declared an uninitialized pointer
queue* columnData;
that has an indeterminate value. So calling the function initQueue
initQueue(columnData, size);
invokes undefined behavior because within the function this pointer is dereferenced.
q->column = new int[size];
q->column[0] = 5;
Also the function does not set the data member arraySize.
You need in main to declare an object of the type queue
queue columnData;
and call the function like
initQueue( &columnData, size);
and within the function you have to set also the data member arraySize like
columnData->arraySize = size;
Pay attention to that this call
printf("%d", &columnData->column[0]);
is also wrong. You are trying to output a pointer using the incorrect conversion specifier %d.
After changing the declaration of the object columnData shown above the call of printf will look like
printf("%d", columnData.column[0]);
Though it will be more consistent to use the overloaded operator <<.

Related

How to create a constructor which takes in a char array?

I have a class, which take in a char array of size specified by a constexpr.
Message.h:
constexpr size_t InputBufferSize = 32;
class Message
{
private:
char input[InputBufferSize];
int size;
public:
//constructor
Message(char input[], int size);
//deconstructor
~Message();
int getSize();
};
I'm confused by how to define the constructor, and then create a new instance of that class using the constructor due to the char array. Here is my try (out of a few things I tried):
Message.cpp:
#include "Message.h"
Message::Message(char input[], int size) {
this->input[InputBufferSize] = input[];
this->size = size;
}
Message::~Message() { }
int Message::getSize() {
return size;
}
main.cpp:
#include <iostream>
#include "Message.h"
int main()
{
char charinp;
char input[InputBufferSize] = { 'a','b','c','d','e','f' };
Message ms1(input[], 1);
std::cout << ms1.getSize() << std::endl;
std::cin >> charinp;
return 0;
}
I'd like to create a constructor with an array as on of its parameters, where the array already has a set size, and then create an object from that. The array to be passed into the object will always be of the same size, which is the size of the array the constructor is set to take in.
Message(char input[], int size);
The use of [] in a parameter declaration is just syntax sugar, the compiler will interpret char input[] as char* input instead.
this->input[InputBufferSize] = input[];
This is not legal code. You need to use (std::)memcpy() or std::copy()/std::copy_n() to copy an array to another array:
memcpy(this->input, input, size);
std::copy(input, input + size, this->input);
std::copy_n(input, size, this->input);
On a side note, you should make sure that size does not exceed InputBufferSize before copying the input array:
size = std::min(size, InputBufferSize);
Message ms1(input[], 6);
This is also not legal code. You need to drop the [] when passing the array to a parameter:
Message ms1(input, 6);
std::cin >> charinp;
On a side note, you can use std::cin.get() instead, and remove charinp from your code (since you don't use it anyway).
You are using Message ms1(input[], 6); in your main function,try changing it to Message ms1(input, 6);.
The reason for this is that you have already declared the array char input[] and you have to refer it as inputafter you have declared it not input[].

correctly declare pointers, allocate memory, and send them as parameters c++

How correctly declare pointers, allocate memory, and send them as parameters in fuctions to write values ? The code below is what I tried but it doesn't work correctly. I need the same logic. I mean declare, set, then show.
...
struct complex {
int i;
int r;
};
void set(complex *n, int i, int r){
n = new complex;
n->i = i;
n->r = r;
}
void show(complex *n){
std::cout << n->i << " " << n->r;
}
int main(int argc, char* argv[])
{
complex *n;
set(n,10,20);
show(n);
system("pause");
return 0;
}
Actually, your function set couldn't work, because by doing
n = new complex;
whatever the pointer you pass to the function, the pointer will be overwritten by the pointer on the new object.
You can pass the pointer via reference (on C++ only...) like that
void set(complex* &n, int i, int r)
And by doing so you'll modify the value of the original pointer.
You can also simply return the pointer by a return n
But obviously if the prototype of your function must stay like that, it's not possible...
Or, but it's highly discouraged, as many said, you can use a double pointer, and it's quite tricky !
If I don't make mistake, you create a
complex** n
You pass it to your function
set(complex** n, int i, int r)
And then you load
*n = new complex
And it must work if you pass *n to all your function instead of n...
And don't forget to delete your object at the end ;)
Remove the initialization part from set function and put it in the main function.
see this link for explanation.
Why can I not initialize an array by passing a pointer to a function?
Check this code
//#include<windows.h>
#include <iostream>
using namespace std;
struct complex {
int i;
int r;
};
void set(complex *n, int i, int r) {
// n = new complex;
n->i = i;
n->r = r;
}
void show(complex *n) {
std::cout << n->i << " " << n->r;
}
int main(int argc, char *argv[]) {
complex *n = new complex();
set(n, 10, 20);
show(n);
delete n;
//system("pause"); TRY TO AVOID THIS. MAKES YOUR CODE LESS PORTABLE.
return 0;
}
see this link.
c++ - system("pause"); - Why is it wrong? - Stack Overflow

How to pass the name of a member from a struct as an argument into a function using C++?

I have exhausted my patience trying to find this particular question .
I am trying to input the name of a particular member from a structure into a function.
My first thought was that this is impossible because a function's arguments needs to be a variable declared and defined in RAM. Yet the computer is able to interpret the location of a "member" for each instance given the members name.
The following is a arbitrary program where I created an array of structures and the program will some how input all of the data for each member in the structure for each instance in the array. It will then attempt to display all of the content for a particular member in the array. It is incomplete because I don't know how to make it work.
#include theUsual
// global variables
const int SIZE = 10;
// structures
struct structureExample
{
dataType member1;
dataType member2;
...
};
// functions
void inputData(structureExample s[], int size);
void displayMember( dataType member, structureExample s[], int size);
int main
{
structureExample sE[SIZE];
dataType memberName = member1 // member1 from the declared struct structureExample
inputData(sE,SIZE);
displayMember(memberName, sE, SIZE);
system("PAUSE");
return 0;
}
// inputs all the data for all members in an array of structure examples
void inputData(structureExample s[], int size)
{
...
}
// display's all of the content of a particular member from an array
void displayMember( dataType member, structureExample s[], int size)
{
for (int i = 0; i<size; i++)
{
cout << s[i].member << endl;
}
}
So given any member name from structureExample into displayMember, it will display the all of the content of that member for every unit in the array.
I have allot of questions about this but the biggest two are, can this even work? If so how could I make this work? Examples would be appreciated.
Thanks in advance!
It seems you want pointer on member:
struct structureExample
{
int member1;
float member2;
};
template<typename M>
void displayMember(M structureExample::*member, structureExample s[], int size)
{
for (int i = 0; i < size; i++)
{
std::cout << s[i].*member << std::endl;
}
}
int main()
{
structureExample sE[SIZE];
auto member = &structureExample::member1;
inputData(sE,SIZE);
displayMember(member, sE, SIZE);
}
Variable names, parameter names, member names, these are all lost during the compiling process, they are translated into memory address offsets. There are no actual names at runtime.
What you are asking for is not possible in C++. You will have to implement your own lookup logic, such as with a std::map, if you need to access values by names determined at runtime, eg:
#include theUsual
#include <map>
#include <string>
// global variables
const int SIZE = 10;
// structures
struct structureExample
{
std::map<std::string, dataType> values;
};
// functions
void inputData(structureExample s[], int size);
void displayMember(const std:string &valueName, structureExample s[], int size);
int main
{
structureExample sE[SIZE];
inputData(sE, SIZE);
displayMember("valueName", sE, SIZE);
system("PAUSE");
return 0;
}
// inputs all the data for all members in an array of structure examples
void inputData(structureExample s[], int size)
{
for (int i = 0; i < size; ++i)
{
...
s[i].values["valueName"] = ...;
...
}
}
// display's all of the content of a particular member from an array
void displayMember(const std::string &valueName, structureExample s[], int size)
{
for (int i = 0; i < size; ++i)
{
std::cout << s[i].values[valueName] << std::endl;
}
}

Arguments passing vs. Variable declaration

What's the difference between passing an argument inside a function as a parameter and declaring the argument as a variable inside the function declaration block in function definition?
Example: Make use of my comments to get the gist of the question.
#include<iostream>
int max=0;
int t=0;
class stack
{
int s[10];
public:
void push(int);
void pop();
};
void stack::push(int y) //argument passed inside function parameter
{
if(t<=max);
{
s[t]=y;
t=t+1;
}
else
cout<<"Stack overflow";
}
void stack::pop()
{
int item; //variable declared inside function definition
if(t>=0)
{
t=t-1;
item=s[t+1];
}
}
One difference is that parameters are initialized by the caller but local variables have to be initialized by the function.
int somefunc(int arg)
{
int local = 0;
…
return local + arg;
}
When the function is called:
int x = somefunc(23);
the variable arg in the function is initialized with the value 23 by the calling code. However, the local variable local has to be explicitly initialized (in this case with the = 0; if it was a class type, by an appropriate constructor). Local variables of built-in types such as int that are not explicitly initialized get a quasi-random value.
One difference is in how arrays are interpreted:
// returns nonzero iff array1 equals {1, 2, 3}
int func(int array1[], size_t size1)
{
int array2[] = {1, 2, 3};
return size1 == sizeof(array2) && memcmp(array1, array2, size1) == 0;
}
While array2 is an array of 3 integers, array1 is an array of unknown size, which is why we usually pass a second parameter for the size. This is because of arrays "decay to pointers" when passed into functions like this. You can read about it here: What is array decaying?
There are fancier techniques for dealing with this in C++ using value templates for the array size, but the above is true of C and most C++ code in the wild too.
Other than arrays, C types used in function parameters behave pretty much the same as C types used in local variables.
The arguments is passed by calling that function. so caller decides what should be passed.
functions decides what should it accept.
for example:
main()
{
int i=0;
int k=i;
for (int j=i; j `enter code here`< n; j++)
{
}
}
is same as
main()
{
int i=0,k;
for (int j=k=i; j < n; j++)
{
}
}
but this
main()
{
int i=0,k;
for (int j=i; j < n; j++)
{
k=i;
}
}
is totally different.

C++ passing an array pointer as a function argument

I'm trying to use pointers of arrays to use as arguments for a function which generates an array.
void generateArray(int *a[], int *si){
srand(time(0));
for (int j=0;j<*si;j++)
*a[j]=(0+rand()%9);
} //end generateArray;
int main() {
const int size=5;
int a[size];
generateArray(&a, &size);
return 0;
} //end main
But when I compile this this message appears:
cannot convert `int (*)[5]' to `int**' for argument `1' to `void generateArray(int**, int*)'
You're over-complicating it - it just needs to be:
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.
int *a[], when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:
int (*aptr)[N]
Where N is a particular positive integer (not a variable).
If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):
template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
for (size_t i=0; i<SZ; ++i)
(*aptr)[i] = rand() % 9;
}
int main()
{
int a[5];
generateArray(&a);
}
You could also take a reference:
template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
for (size_t i=0; i<SZ; ++i)
arr[i] = rand() % 9;
}
int main()
{
int a[5];
generateArray(a);
}
You do not need to take a pointer to the array in order to pass it to an array-generating function, because arrays already decay to pointers when you pass them to functions. Simply make the parameter int a[], and use it as a regular array inside the function, the changes will be made to the array that you have passed in.
void generateArray(int a[], int si) {
srand(time(0));
for (int j=0;j<*si;j++)
a[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
As a side note, you do not need to pass the size by pointer, because you are not changing it inside the function. Moreover, it is not a good idea to pass a pointer to constant to a parameter that expects a pointer to non-constant.
I'm guessing this will help.
When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type:
int x[]
or
int x[a]
. Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.
This is another method . Passing array as a pointer to the function
void generateArray(int *array, int size) {
srand(time(0));
for (int j=0;j<size;j++)
array[j]=(0+rand()%9);
}
int main(){
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}