Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a header file abc.h
//abc.h
unsigned int *get(void)
{
static unsigned int input[] =
{
1,
2, 2,
4, 5,
6, 7
};
return input;
}
Now, i want to read this input(from header file,not from some text file) into my main cpp file say xyz.cpp
I am thinking of using an array to access these elements,but i don't think it will work.
int arr[6];
arr=get();
The first element is number of test cases n,the second and third element are dimensions of 2-D array and the rest of the elements are the values of 2-D array.So i need to input value of n,rows,columns and values for 2D array arr[rows][columns]
Any ideas on how can i achieve this?
EDIT: I seriously can't figure out why this question is getting downvoted.
I agree this is not a good implementation,but I have been given an input header file and i can read data only through this header file!!
If you able to compile your programm with this file, you does not need to read anything. This array and it values will be compiled into your programm and you can access them right in place
Your xyz.cpp file should look like:
#include "abc.h" // given abc file located in the same directory
int main(){
unsigned int * myArrayPtr = get();
// here comes some processing and, if you want, reading values from this array;
unsigned int numberOfCases = myArrayPtr[0];
unsigned int * dimensionsArrayPtr = myArrayPtr + 1;
unsigned int xArraySize = dimensionsArrayPtr[0];
unsigned int yArraySize = dimensionsArrayPtr[1];
// and etc.
// Most interesting part to represent those values as two dimensional array
// I left to you :)
return 0;
}
Also, you should remeber that this trick could work only because array in header file declared as static. Otherways your programm would have undefined behavior.
One more also. If your function body defined in header file, you should declare it inline.
As long as this header included only on one cpp file - its all right. But when it will included to more the one code file, you will get already defined linker error.
I recommend you to learn more about pointers in cpp. This article is fine enough http://www.cplusplus.com/doc/tutorial/pointers/
About static keyword - to fully understand this example - there is fine answer on SO itself
The static keyword and its various uses in C++
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am new to C++ and have come across the const keyword. I looked it up online and read that The main use is to prevent the changing the value throughout the program. I have these two snippets below
const int size = 56;
Compared to using
int size = 56;
Why should I use one over the other? What is the idea behind using it.
Yes, you should make all variables const if you are never going to change its value after initialization. This prevents bugs where you accidentally change a value you're not supposed to. You seem to be aware of this already.
In addition, there is something that you might not be aware of, which is that making an int variable const also makes it a constant-expression, so long as the initializer itself is also a constant-expression, e.g. the int literal 56. This allows you to use it in contexts where you need a constant-expression, e.g. as the dimension of a static array:
const int size = 56;
int a[size]; // ok
int size = 56;
int a[size]; // error
In c++ CONST is used when you want to declare something which will not change its value throughout the program. But if you accidentally try to rewrite its value, the compiler will through an error. Most of the time it is recommended to declare a variable of int type so you can redefine its value when it's required. CONST is used when you want to declare a static array i.e.
const int a = 100;
int sampleAray[a];
And int is used when you, the value of the variable will be modified at some point i.e.
int a = 12;
int arr[4] = {11,22,33,554};
for (int i=0; i<4; i++){
if(arr[i]%2 == 0){
a+=arr[i];
}
}
When you have a const variable holding something that should not change and accidentally write code that modifies the variable anyway, you get a nice compiler error and can correct your mistake easily. If the variable is non-const, the compiler cannot help you and you now have a bug that may be hard to find.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I got an array at the end of my class and i don't know how to use it.
the bus[10] is so hard to understand. I don't know why it can access driver and what does empty() function really do.
#include "conio.h"
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#include "graphics.h"
#include "stdlib.h"
#include "dos.h"
static int p=0;
class a
{
char driver[10];// driver
public:
void install();// for installing
}bus[10];//here we declare the number of buses we can have.
void a::install()
{
cout<<"Enter bus no: ";//ques
cin >> bus[p].driver;// what does this mean
bus[p].empty();//what does this mean
p++;
}
This is syntax for defining a type, and an instance of that type, at the same time.
For example:
struct Foo {} foo;
is the same as:
struct Foo {};
Foo foo;
So your example defines the type a, and also creates an array of 10 as called bus.
It would be more clearly written thus:
class a
{
char driver[10];
public:
void install();
};
a bus[10];
In this manner we can now more easily see that you've created a global array called bus, which you can use like you'd use any other array.
Since p is zero (to begin with), bus[p] just gives you the "first" a object in the array (to begin with). As p is increased, subsequent buses are accessed.
So, this:
cin >> bus[p].driver;
reads into the driver member of the pth bus.*
And this:
bus[p].empty();
means nothing, because a does not have a member function called empty().
* Well, the p+1th bus, because array indices begin at zero but English doesn't!
P.S. You can do funny (read: stupid) things with this syntax!
This is a very strange looking code, probably from an old workbook.
I could help you with achieving the action that you want, but it's hard to understand anything from this snippet.
Wrong: As far as I remember adding a identifier at the end of an unnamed struct gave it a name just like the usual approach.
struct {
float x, y;
} Point;
//is equal to
struct Point {
float x, y;
}
However I'm not familiar with the array syntax you provided.
I suppose std::cin >> bus[p].driver is meant to read the "name" that the char[10] driver field is. But using a char array here is troublesome and it's much better to replace it with std::string and shortening it to 10 characters after input.
The empty() method is often used as a container function returning boolean and telling the programmer whether the container is empty or not. Here however this function is undeclared and the code won't compile either way.
Not to mention that non-const variables placed out of function scope, like the static int p = 0, are a grave mistake.
Not true: In conclusion this is a very messy code and without the knowledge of what you want to achieve nobody could help you here.
See the answer below for better explanation.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
It's been a while since I have worked in C++, I am helping a friend.
Is there a way without pointers return number of lines to a const int for use in a for loop?
I know I can do it with pointers but he has not learned them in class yet and I am not morally allowed to teach him anything the professor hasn't.
Example:
int numLines = sizeOfFile(inputFile);
for(int i = 0, i < numLines; i++){
//code here
}
EDIT: my fault I was moving fast to code this thing. I am helping him today I want to have a finished project so I can work off of it while helping him. The reason I need a constant int is so I can set array to that size not just for a for loop. the array is the problem.
You can initialize a const int just the same as you would initialize a regular int. The difference with a const int is that you cannot re-assign after initialization.
const int numLines = sizeOfFile(inputFile);
for(int i = 0, i < numLines; i++){
//code here
}
In the simplest case you're just looking for the number of '\n' characters in the file.
So let's say that you've successfully opened the file to: ifstream pFile then you can use an istreambuf_iterator to count those:
const auto numLines = count(istreambuf_iterator<char>(pFile), istreambuf_iterator<char>(), '\n')
A couple comments here:
The this count operation will consume everything in pFile's buffer, meaning you'll need to call pFile.seekg(0, ios_base::beg)
Picking and choosing values to read from an ifstream indicates a bad smell in code. It's likely that the file format was improperly conceived, or that the program will subsequently need to re-stream the remainder of file contents. The 2nd option seems to be true in your case, as you seek to illegally set the size of an array with a value found at runtime:
The reason I need a constant int is so I can set array to that size
EDIT:
When you say you want to use numLines to "right an array"[sic], my assumption is that the only reason that you would have needed your array to be that size is that you're going to stream each line from a file into your container, that is you're going to stream the entire file once to calculate the size then stream the entire file again to populate your container. Here's what you should do instead:
vector<string> lines;
for(string line; getline(pFiles, line);) {
lines.push_back(line);
}
Now lines will contain your entire file, with each element being a line. If numLines would have been important to you, instead you can use size(lines).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is my code:
The marked line is giving the error.
class Student{
public:
//Student(string x, int y, string z[]);
void getinfo();
void printinfo();
private:
string name;
int numClasses;
string arr[numClasses]; // the error is here it's not allowing me to put numClasses as the size of
// the class
};
The size of the array must be a constant integral expression
You can do something like this:
class Student
{
public:
void getinfo();
void printinfo();
private:
string name;
static const int numClasses = 20;
string arr[numClasses];
};
Since, the array will be allocated at compile time, and so when the size is not a constant, the compiler cannot accurately determine its value and throws error.
if you want to use array with dynamic size, use vector.
Here,
1) Change size to const
2) or, use vector -> vector<string>arr;
Array should be constant here is some explanation that can help that I found in cpp website
The elements field within brackets [] which represents the number of
elements the array is going to hold, must be a constant value, since
arrays are blocks of non-dynamic memory whose size must be determined
before execution. In order to create arrays with a variable length
dynamic memory is needed
since you have got your answer already I am just going to include great information about arrays that other might benefit from.
in c++ correct way to declare an array of 10 integers for example can be done this way
int array[10];
if you know a head of time what values you want in the array you can just do it this way
int numbers [] = {13, 30, 50, 2, 5, 6, 70, 8, 9, 10};
"Pointer arithmetic" & regular arithmetic
Pointer arithmetic is a way of expressing evaluations it uses 2 stacks one for characters and one for numbers for example pointer arithmetic uses *(a+1)" where as regular arithmetic uses "a[i]"
both are the same
one of my professors talked a lot about arrays
and say array[i] = *(a+i)
what does that mean?
it basically means
if a[i] = a[0]
then in pointer arithmetic it is :
*(a+0);
and if a[i] = a[1]
then in pointer arithmetic it is :
*(a+1); and so on
basically I shared about 2 weeks of my data structure course :P
hope I was able to help
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I know how to code with C++, however this is my first time I try to use C.
I even tried to define a cVector.h and cVector.c in order to implement some of the std::vector functionality. but when I compile my code I receive the following error.
Here is same of the code:
cVector.h
#define VECTOR_INITIAL_CAPACITY 520
typedef struct {
int size; // slots used so far
int capacity; // total available slots
int *data; // array of integers we're storing
} Vector;
void vector_init( Vector *vector);
cVector.c
#include "cVector.h"
#include <stdio.h>
#include <stdlib.h>
void vector_init(Vector *vector) {
// initialize size and capacity
vector->size = 0;
vector->capacity = VECTOR_INITIAL_CAPACITY;
// allocate memory for vector->data
vector->data = malloc(sizeof(int) * vector->capacity);
}
here is the usage:
#include "cVector.h"
Vector times;
vector_init(×);
int main{
....}
and finally error:
Ser.c:135:13: error: expected declaration specifiers or ‘...’ before ‘&’ token
You can't call a function at file scope like that. You need to move the call into a function (e.g. main).
You can't use a function outside the declaration of another function. Btw you can declare variables as globals variables but the line
vector_init(×);
must be written inside of the main function.
If you are interested the gcc's error message it's because of he is trying to find the declaration of a new function, this is, the name of a type or ... instead.