Assign value to dynamically allocated integer - c++

UPDATE:
Thanks to everyone for the help to understand this!
I try to run this:
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
and i get the following errors:
1>------ Build started: Project: learnCpp, Configuration: Debug Win32 ------
1>learnCpp.cpp
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,2): error C2374: 'x': redefinition; multiple initialization
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(3): message : see declaration of 'x'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,7): error C2440: 'initializing': cannot convert from 'int' to 'int *'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,4): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "learnCpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
however I don't get any errors if I assign the value to x inside the main function.
Like so:
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
How come?

In the file scope in C you may place only declarations. You may not execute statements in the file scope. The same is valid for C++ where you may place in a namespace only declarations.
Note: In C declarations are not statements while in C++ declarations are statements. Nevertheless except the declaration statement other statements may not be present in a namespace in C++. It is interesting also to note that in C there is a null statement but there is no an empty declaration. While in C++ there may be an empty declaration.
So this program
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
is invalid.
These error messages of the compiler
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2374: 'x': redefinition; multiple initialization
message : see declaration of 'x'
mean that the compiler tries to interpret the assignment statement as a declaration.
But this program
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
is correct. In this program the assignment statement is present in the outer block scope of the function main.

What you are trying to do is not possible in global scope.
If you need to do this way try to initialize as below :
// good practice
namespace
{
int* x = new int(5);
}
int main()
{
// You can later modify in function scope
*x = 10;
}

You cannot have statements other than declarations, outside of any scope (for simplicity consider a scope whatever is inside brackets). So, compiler is trying to interpret
*x = 5;
as a declaration, so as a pointer to a given type, but does not find the type pointed to, so generates an error.

Related

Error facing with range function in DPC++

I'm new to Sycl/DPC++ language. I wrote a sample vector addition code using Unified shared memory (USM):
#include<CL/sycl.hpp>
#include<iostream>
#include<chrono>
using namespace sycl;
int main()
{
int n=100;
int i;
queue q{ };
range<1>(n);
int *a=malloc_shared<int>(n,q);
int *b=malloc_shared<int>(n,q);
int *c=malloc_shared<int>(n,q);
for(i=0;i<n;i++)
{
a[i]=i;
b[i]=n-i;
}
q.parallel_for(n,[=](auto &i){
c[i]=a[i]+b[i];
}).wait();
for(i=0;i<n;i++){
std::cout<<c[i]<<std::endl;
}
free(a,q);
free(b,q);
free(c,q);
return 0;
}
When I compile it I get the following error:
warning: parentheses were disambiguated as redundant parentheses around declaration of variable named 'n' [-Wvexing-parse]
range<1>(n);
^~~
vec_add.cpp:11:1: note: add enclosing parentheses to perform a function-style cast
range<1>(n);
^
( )
vec_add.cpp:11:9: note: remove parentheses to silence this warning
range<1>(n);
^ ~
vec_add.cpp:11:10: error: redefinition of 'n' with a different type: 'range<1>' vs 'int'
range<1>(n);
^
vec_add.cpp:8:5: note: previous definition is here
int n=100;
^
1 warning and 1 error generated.
How to fix this error?
error: redefinition of 'n' with a different type: 'range<1>' vs 'int'
Two variables with the same name within the same scope create confusion to the compiler, so it might be the reason for the error which you are getting. You can try defining the value of n globally say for eg: #define N 100 in this case, set
range<1>(n);
to
range<1> (N);
and use that in your code.
If you want to declare the size locally then assign another variable (r) to the range as
range<1> r (n);
Now you can directly pass the 'r' variable as a parameter to the parallel_for.

Pseudo-code given in class that I'm trying to comprehend with the associated lab assignment in c++

So I've tried to figure out what exactly the professor was writing on the board and how it answers the lab assignment we are to do.
This is the lab assignment:
Create a Hash Table and Hash map that holds all of the WORDS in the (given below) Declaration of Independence.
Handle collisions using the chain method. (Note we will not be modifying this table nor doing deletions!)
Programmatically answer the following questions:
What is the size of your hash table?
What is the longest collision (ie. Chain)
What is the most frequently used word and how did you determine it?
Create a (second) Hash Table that holds all of the LETTERS in the Declaration of Independence.
What is the size of your hash table
What letter has the longest collision?
And this is the pseudo-code with some modifications that I did to fix some errors:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
class Translate
{
string word;
public:
int trans(string word);
w = word.charAT(0); //gives a letter
return #num;
};
class HashTable
{
int size();
int collision();
int length();
char fword();
public:
Translate t;
list<string> hashTable[29];
bool insert(string word)
{
hashTable[t.trans(word)].push_back(word);
return true;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HashTable h;
open file f("hash.txt");
//h.insert(word)
while (!f.eof())
{
h.insert(f.word());
}
cout << h.size;
cout << h.collision.length;
cout << h.fword;
return 0;
}
The errors that I have are:
Error 15 error C1903: unable to recover from previous error(s); stopping compilation
Error 5 error C2014: preprocessor command must start as first nonwhite space
Error 4 error C2059: syntax error : 'return'
Error 13 error C2065: 'f' : undeclared identifier
Error 10 error C2065: 'file' : undeclared identifier
Error 8 error C2065: 'open' : undeclared identifier
Error 6 error C2143: syntax error : missing ';' before '}'
Error 1 error C2143: syntax error : missing ';' before '='
Error 11 error C2146: syntax error : missing ';' before identifier 'f'
Error 9 error C2146: syntax error : missing ';' before identifier 'file'
Error 14 error C2228: left of '.eof' must have class/struct/union
Error 3 error C2238: unexpected token(s) preceding ';'
Error 7 error C2238: unexpected token(s) preceding ';'
Error 12 error C3861: 'f': identifier not found
Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 19 IntelliSense: '#' not expected here
Error 17 IntelliSense: class "std::basic_string, std::allocator>" has no member "charAT"
Error 21 IntelliSense: expected a ';'
Error 18 IntelliSense: expected a declaration
Error 22 IntelliSense: identifier "f" is undefined
Error 20 IntelliSense: identifier "open" is undefined
Error 16 IntelliSense: this declaration has no storage class or type specifier
I've never used .c_str and I'm still pretty new to C++ so my knowledge is limited. I can tell that there are places that need an identifier but I think there is a better way to create a "open file". My previous knowledge is C#, HTML, and some Python in which C++ is giving me some difficulty in learning and understanding. Any help and/or insight would be greatly appreciated!
Code is too mangled to understand. However, I'm trying my best to help with the little knowledge of mine on C++ and hash.
Proposed Code Modification
Program entry point : instead of int _tmain(int, _TCHAR*), use int main().This should guarantee you the ability to test things out should you migrate to non-windows compiler.
Source : Unicode _tmain vs main
I would like to help with the remainder, however, the code posted is way too unintelligible. Would be kind if the algorithm is posted for reference.
There are a few things you should change:
Assuming trans() is supposed to be a function definition, not a declaration, and the lines following it are supposed to be the body:
Unless you specifically want to copy the passed string, you should use const string& instead of string.
It should have braces.
w is a char.
std::string defines operator[], so it can be indexed like an array.
I'm not sure what #num is (I assume it's from Python, but I'm not familiar with that), so I'm not sure how you intend to calculate the return value.
[I will thus assume that you want to return w, but as an int instead of a char. If this is the case, it would be simpler to just return word[0];.]
There are a few issues with HashTable's members.
Member functions size(), collision(), length(), and fword() are private. This doesn't appear to be intentional.
Member variables t and hashTable are public, when you likely wanted them to be private. Again, this doesn't appear to be intentional.
The functions aren't actually defined anywhere, unless you didn't show their definitions. This will cause a linking error when you call them.
While this doesn't need to be changed, there's no reason for HashTable::insert() to actually return a value, if it's hard-coded to always return true. Also, as mentioned in 1.1 above, the parameter should probably be const string&.
_tmain() and _TCHAR are a Microsoft extensions, which is available on Visual Studio and some (but not all) compilers aiming for compatibility with it (such as C++Builder). If you want your code to be platform-independent, you likely want main(). [Note that this doesn't need to be changed. If you're only compiling with Visual Studio, you can leave it as is. If you want platform independence, you can easily define _tmain and _TCHAR yourself.]
Opening a file:
Neither open nor file are keywords in C++, nor are they types (although FILE is a C type, it doesn't appear to be what you want). You appear to want std::ifstream.
You shouldn't use !f.eof() as a condition in a while loop, because eofbit won't be set until after reading fails.
fstream has no member function word(). However, the extraction operator, operator>>() will read a single word at a time, if given a parameter that can accept one.
HashTable::size(), HashTable::collision(), HashTable::length(), and HashTable::fword() are functions. To call them, you use operator(). If you just use a function's name directly, you don't call it, but instead refer to it (this can be used to create a function pointer or function reference).
int has no member function length(). Therefore, you cannot call h.collision().length(). In C++, if you chain function calls like that, each function in the chain is treated as if it were a member function of the directly preceding type, not the leftmost type; this means that for every function after the first, the return type of the preceding function is used. (In this case, h.collision() returns an int, so .length() attempts to call member function int::length(). int isn't a class type, and thus doesn't have any member functions.)
So, considering these, your code can be modified as follows:
// Assuming your stdafx.h contains "#include <string>" and "#include <tchar.h>".
// If it doesn't, either put them there, or #include them here.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
// #4: Defining _tmain and _TCHAR
#ifndef _tmain
#define _tmain main
typedef char _TCHAR;
#endif
using namespace std;
class Translate
{
string word;
public:
// #1: Fixing trans().
int trans(const string& word)
{
char w = word[0]; // First letter of word.
return w; // Will be promoted to int.
}
};
class HashTable
{
// #2: Making member functions public, and member variables private.
Translate t;
list<string> hashTable[29];
public:
int size();
int collision();
int length();
char fword();
// #3: Making word a const reference. Changing return type to void.
void insert(const string& word)
{
hashTable[t.trans(word)].push_back(word);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HashTable h;
// #5.1: Opening the file.
ifstream f("hash.txt");
//h.insert(word)
// #5.2 & 5.3: Reading a word.
std::string word;
while (f >> word)
{
h.insert(word);
}
// #6: Calling functions.
cout << h.size();
cout << h.collision(); // #7: Assuming you wanted to output both h.collision() and
cout << h.length(); // h.length(), I put them on separate lines.
// If you actually DID want h.collision().length(), then
// h.collision() should return a type (or reference to a type)
// with member function length(), or be an instance
// (or reference to an instance) of a class with member function
// length() (instead of being a function).
cout << h.fword();
return 0;
}
You still need to provide bodies for HashTable's member functions, apart from insert(), as well as make any other modifications you desire. You might also want to remove member word from Translate, if it doesn't actually need to store a string.

initializing variable in different-different position in windows is giving error

I am initializing simple int variable in my code but it gives some unwanted errors... If I use integer(or other data type) variable in some places it gives error. I write down my code and put comment where integer variable is showing error.
#include<stdio.h>
#include<Windows.h>
//int i; ///********* no problem ************
int main()
{
//int i; ///********* no problem ************
STARTUPINFO si;
PROCESS_INFORMATION pi;
//int i; ///********* no problem ************
ZeroMemory(&si,sizeof(si));
//int i; // error C2143: syntax error : missing ';' before 'type'
si.cb=sizeof(si);
//int i; //error C2143: syntax error : missing ';' before 'type'
ZeroMemory(&pi,sizeof(pi));
//int i; //error C2143: syntax error : missing ';' before 'type'
if(CreateProcess("C:\\Windows\\System32\\notepad.exe",NULL,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,NULL,&si,&pi))
{
//int i; ///********* no problem ************
printf("process created\n pid is=%d tid is=%d\n",pi.dwProcessId,pi.dwThreadId);
}
else
{
//int i; ///********* no problem ************
printf("process creation error\n");
}
// int i; // error C2143: syntax error : missing ';' before 'type'
}
I am using cl.exe compiler and visual studio 2012.I am compiling code from command line
cl process.c
The Visual Studio compiler doesn't support C99, which you are attempting to use.
You must use just C90, i.e. keep your variable declarations at the top of their containing scope.
You must declare all your variables just after the { of a function.
This is because Visual Studio supports C89 and C89 forbids mixed declarations. In C99 and later,variables can be declared anywhere

Array of Pointers assigning value

Works:
int GlobalVar = 5;
int * LPVar[] = {&GlobalVar};
Doesn't work:
int GlobalVar = 5;
int * LPVar[]; // int * LPVar[1] doesn't work too
LPVar[0] = &GlobalVar; // errors here
------ Build started: Project: pointers, Configuration: Release Win32 ------ Compiling... ilovpointers.cpp .\ilovpointers.cpp(9) : error C2466: cannot allocate an array of constant size 0
.\ilovpointers.cpp(9) : error C4430: missing type specifier - int
assumed. Note: C++ does not support default-int .\ilovpointers.cpp(9)
: error C2040: 'LPVar' : 'int []' differs in levels of indirection
from 'int *[1]' .\ilovpointers.cpp(9) : error C2440: 'initializing' :
cannot convert from 'int *' to 'int []'
There are no conversions to array types, although there are conversions to references or pointers to arrays Build log was saved at
"file://f:\Visual Studio
C++\Project1\pointers\pointers\Release\BuildLog.htm" pointers - 4
error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
EDIT:
I solved but got question.
#include <iostream>
#include <stdio.h>
using namespace std;
int GlobalVar = 5;
int * LPVar[1];
void main()
{
LPVar[0] = &GlobalVar;
printf("%i", *LPVar[0]);
cin.get();
}
LPVar is a global array so why it didn't work when I have put it just after definition?
Is the code at file scope?
The answer appears to be yes given the updated code fragment.
If so, you can't have random assignments like LPVar[0] = &GlobalVar; written at file scope. You can only have declarations (without initializers) or definitions (optionally with initializers) at file scope.
In your question, this works (as indeed it should), because there are two variable definitions with initializers.
int GlobalVar = 5;
int *LPVar[] = {&GlobalVar};
This code does not work (as indeed it shouldn't), because the third line is an assignment statement and not a declaration or definition:
int GlobalVar = 5;
int *LPVar[]; // Declaration, not definition
LPVar[0] = &GlobalVar; // Assignment is not allowed outside a function body
Variant:
int GlobalVar = 5;
int *LPVar[1]; // Definition without initializer
LPVar[0] = &GlobalVar; // Assignment is not allowed outside a function body

Basic pointer to array of class for c++

AIBase* allai[2];
AIBase *z0AI = new AIA;
AIBase *z1AI = new AIB;
allai[0] = z0AI;//this this gives me an error
allai[1]= z1AI;
AIBase is the superclass and AIA and AIB inherits from the AIBase
what is wrong with the syntax ,i need some help in figuring this out
error 1:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2466: cannot allocate an array of constant size 0
error C2040: 'allai' : 'int []' differs in levels of indirection from 'AIBase *[2]'
Why must this code be in function scope? Cant this work in global scope?
In C++ (and C), executable code that is not a variable initialiser must appear inside a function. Executable code cannot appear at file scope (that is, outside any function).
So, just put your code inside a function:
int main(int, char *[])
{
AIBase* allai[2];
AIBase *z0AI = new AIA;
AIBase *z1AI = new AIB;
allai[0] = z0AI;
allai[1]= z1AI;
}