Creating my own std::vector in C program [closed] - c++

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(&times);
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(&times);
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.

Related

Is there anyway for the array at the end of class to work? [closed]

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.

How Integers initialize in C++? [closed]

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 4 years ago.
Improve this question
#include <iostream>
#include <math.h>
using namespace std;
class ip{
private:
string ip;
int result[8];
int sum;
public:
void input(){
/* cout<<"Enter First 8 Binary in Ip address: ";
cin>>ip;
for(int i=0,j=7;i<8 ,j>=0;++i,--j){
if(ip[i]=='1'){
result[i]=pow(2,j);
}else if(ip[i]=='0'){
result[i]=0;
}
}
for(int i=1 ; i<8 ; ++i){
sum=sum+result[i];
} */
cout<<sum<<"\n";
}
};
int main() {
ip convert;
convert.input();
return 0;
}
I was getting some problem while running this code then I understood the problem is with integer initialization...
please help me as I'm getting unwanted output
after running this code my output is: 131
I expected '0' as output
why is it so
You're right, one problem is that you don't initialise sum to zero. Also int i = 1 should surely be int i = 0.
sum=0;
for(int i=0 ; i<8 ; ++i){
sum=sum+result[i];
There are lots of other problems with the code including unnecessary use of a class, unnecessary use of class variables, unnecessary use of floating point functions, unnecessary use of temporary array etc. etc. This program could be much simpler.
In C++, Automatic storage duration integer variables are not initialized to any particular value, and will contain whatever garbage bit pattern that happens to already be in those memory locations. From the perspective of the language standard, the value of the variable is indeterminate, and using it leads to undefined behavior. If you had defined it as a static variable, it would be auto-initialized to 0 in C++.
Most likely your compiler will also throw a warning if you try to use a uninitialized variable.
In GCC, you will see the warning if you compile with below flag:
-Wuninitialized
Warn if an automatic variable is used without first being initialized or if a variable may be clobbered by a setjmp call. In C++, warn if a non-static reference or non-static const member appears in a class without constructors.
Update based on Peter's comment:
In the above case, the code creates an automatic storage duration object of that class type. However, since you just declare an object of type ip as ip convert and you don't have your own constructor which initializes class objects' member values, compiler's default constructor will be called. Most compilers (if not all) will not initialize member values for you and hence you see an output corresponding to the bit pattern present in the memory locations where the object got created.

How to copy char * to an array of 16 bytes [closed]

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 4 years ago.
Improve this question
How to copy char * to an array of 16 bytes.
const char *SK = "1234456789999978";
sample_aes_gcm_128bit_key_t alice[16];
memcpy(alice, (sample_aes_gcm_128bit_key_t*)SK, 16); //gives error
Definition of sample_aes_gcm_128bit_key_t
typedef uint8_t sample_aes_gcm_128bit_key_t[16];
Error:
error: expected constructor, destructor, or type conversion before ‘(’ token
memcpy(alice, (sample_aes_gcm_128bit_key_t*)SK, 16);
This works for me:
#include <iostream>
#include <cstring>
int main()
{
typedef int sgx_aes_gcm_128bit_key_t;
const char *SK = "1234456789999978";
sgx_aes_gcm_128bit_key_t alice[16];
std::copy(SK, SK + strlen(SK), alice);
for(auto& i : alice){
std::cout << i - '0';
}
return 0;
}
Take care that your typedef name matches the name you use. (It didn't in question.) And you can remove the cast to sgx_aes_gcm_128bit_key_t. Hopefully this accomplishes what you're trying to do.
If you want to use memcpy with C++, that is fully possible. Inside memcpy you should use casts to (void*)
memcpy((void*)alice, (void*)SK, 16);
Make sure to get types and size right to prevent segmentation fault.

What is the difference between constant declaring Global or declaring inside a function where it is used [closed]

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 5 years ago.
Improve this question
i am declaring a constant (a large structure constant containing string) inside a function and it is used only inside this function.
will it have any execution time impact on my program? '
They will be created every time the function is called (take more time) or only once and the reference will be used through out its life.
If i declare the constant outside the function (global) will it be faster in execution ?
Actually, declaring variables inside of a function is a great practice. If that variable is only to be used inside of that function of course. There won't be any performance differences between the two methods, but making the constant global may require a more creative naming scheme while the one inside the function can be generic. It is only being used inside of that function, after all.
static struct can help you setting it up once and be done with it. This will be coming from data segment and initialise during at the startup. A raw and dirty code below, but will give you some intuition.
#include <stdio.h>
struct A {
int a;
int b;
};
void func(void)
{
static struct A a = {5,3};
printf("FUNC: A.a: %d\n", a.a);
}
int main(int argc, char **argv)
{
static struct A a = {6,4};
printf("MAIN: A.a: %d\n", a.a);
func();
return 0;
}
I would personally move it out of the function body if any other related functions use the variable, as long as you're using namespaces.
Also if its a true constant, I believe you can declare a struct static constexpr, which means that it won't be allocated on the stack every time the function is called (static), even if you declare it inside the function body. It also means that where it can be used at compile time, it will be (constexpr).
#include <iostream>
namespace Test{
struct Test {
char name[11];
int a;
int b;
};
static constexpr Test TEST_CONSTEXPR = {
"test value",
5,
6
};
}
int main()
{
std::cout << Test::TEST_CONSTEXPR.name << std::endl;
std::cin.get();
return 0;
}
In Ada this is compiler dependent. (As performance usually is.)
As "constants" are not compile-time static, a compiler may do the safe thing and evaluate the initialising expression every time the constant is declared.
If it really matters, measure what your compiler does.

Why is my program giving ambiguous reference to wstring error? [closed]

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
Why is the following code is giving this error:
reference to ‘wstring’ is ambiguous; i = wstring(ws);
I don't have any other function named wstring to cause the ambiguity.
int wstring(string &act)
{
int i=0;
vector<int> hash;
while(act[i++]!='\0')
if(act[i]=='#')
{
hash.push_back(i);
cout<<i<<endl;
}
return i;
}
int main()
{
int cases, i;
string ws;
cin>>cases;
while(cases--)
{
getline(cin, ws);
i = wstring(ws);
cout<<i;
}
return 0;
}
In the beginning of your code, do you have using namespace std?. Because if so, the call is ambiguous. You can fix it through:
i = ::wstring(ws);
namespace std has the same name as a typedef for std::basic_string<wchar_t> (i.e std::wstring). You have a name conflict because the compiler doesn't know if you meant wstring(ws) as a cast-expression to a std::wstring object or a function call. This is why, for one, using namespace std is not recommended, and why giving names to objects that have similar names in the global namesapces causes ambiguity.
I am assuming you also have at the top of your file
#include <string>
using namespace std;
This is where your ambiguous call to wstring exists. wstring is a type declared in string and the compiler can't tell if you mean the function wstring or if you want to create an object of type wstring and convert it to an int.