Issue With struct - struct

I am running this simple code to be used in segment trees. Shows a lot of errors. Could anyone explain where am I going wrong here? It basically has problems with declaring a vector of nodes.
`
// C++ program to show segment tree operations like construction, query and update
#include <bits/stdc++.h>
using namespace std;
struct node{
int open, closed, full;
node(int op, int cl, int f){
open = op;
closed = cl;
full = f;
}
};
void printseg(vector<node> &v){
for(auto it: v){
cout<<it.open<<" ";
cout<<it.closed<<" ";
cout<<it.full;
}
cout<<"\n";
}
void build(int index, int low, int high, string s, vector<node> seg){
if(low==high){
seg[index] = node(s[low] == '(', s[low] == ')', 0);
return;
}
int mid = (low+high)/2;
build(2*index+1, low, mid, s, seg);
build(2*index+2, mid+1, high, s, seg);
seg[index] = merge_nodes(seg[2*index+1], seg[2*index+2]);
}
void solve4(){
string s;
cin>>s;
int n = s.size();
vector<node> seg(4*n);
build(0, 0, n-1, s, seg);
printseg(seg);
}
`

Related

Line 1034: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebebe for type 'int', which requires 4 byte alignment

I'm getting runtime error for this problem 01 Matrix (https://leetcode.com/problems/01-matrix/description/ Can anyone check what's wrong with my code/logic?
My code:-
class Solution {
public:
int f(int i,int j,vector<vector<int>>& mat,vector<vector<int>>&dp){
if(i<0 or i>mat.size())return -1;
if(j<0 or j>mat[0].size())return -1;
if(mat[i][j]==0){
return 0;
}
if(dp[i][j]!=-1) return dp[i][j];
int l=f(i,j-1,mat,dp);
int r=f(i,j+1,mat,dp);
int u=f(i-1,j,mat,dp);
int d=f(i+1,j,mat,dp);
return dp[i][j]=1+min({l,d,r,u});
}
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int n=mat.size();
int m=mat[0].size();
vector<vector<int>> v(n+1,vector<int>(m+1,0));
vector<vector<int>> dp(n+1,vector<int>(m+1,-1));
for(int i=0;i<mat.size();i++){
for(int j=0;j<mat[0].size();i++){
v[i][j]=f(i,j,mat,dp);
}
}
return v;
}
};
I tried running the code and I was getting an error(as pasted above) Can someone help me?

Function won't reverse strings properly

#include <iostream>
#include <cstring>
using namespace std;
void reverseString(char s[])
{
int length = strlen(s);
for (int i = 0; s[i] != '\0'; i++) {
char temp = s[i];
s[i] = s[length - i - 1];
s[length - i - 1] = temp;
cout << s[i]; //this ends up printing "eooe" instead of reversing the whole string
}
}
int main()
{
char a[] = "Shoe";
reverseString(a);
return 1;
}
I'm wondering where the algorithm messes up and what I can do to fix it, maybe I overlooked something because when I try to solve it on a piece of paper it appears to work correctly.
Your algo is right but need a little modification, you have to run algorithm for length/2 times. It prevents your string to again swap the contents i.e At i = 2 your s = eohs but it again swaps h with o. Try to insert the break point to understand it further. I modify your function little bit.
char* reverseString(char s[])
{
int length = strlen(s);
for (int i = 0; i<length/2; i++)
{
char temp = s[i];
s[i] = s[length - i - 1];
s[length - i - 1] = temp;
//cout << s[i]; //this ends up printing "eooe" instead of reversing the whole string
}
return s;
}
int main()
{
char a[] = "Shoe";
cout<<reverseString(a);
system("pause");
return 1;
}
Use the code below:
#include <stdio.h>
void strrev(char *p)
{
char *q = p;
while(q && *q) ++q;
for(--q; p < q; ++p, --q)
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
int main(int argc, char **argv)
{
do {
printf("%s ", argv[argc-1]);
strrev(argv[argc-1]);
printf("%s\n", argv[argc-1]);
} while(--argc);
return 0;
}

CUDA copy linked lists from device to host

I am trying to populate a number of linked lists on the device and then return those lists back to the hosts.
From my understanding I need to allocate memory for my struct Element, but I don't know how to go about it since I will have many linked lists, each with an unknown number of elements. I've tried a couple of different things but it still didn't work. So I'm back to the starting point. Here is my code:
//NODE CLASS
class Node{
public:
int x,y;
Node *parent;
__device__ __host__ Node(){}
__device__ __host__ Node(int cX, int cY){x = cX; y = cY;}
__device__ __host__ int get_row() { return x; }
__device__ __host__ int get_col() { return y; }
};
//LINKED LIST
class LinkedList{
public:
__device__ __host__ struct Element{
Node n1;
Element *next;
};
__device__ __host__ LinkedList(){
head = NULL;
}
__device__ __host__ void addNode(Node n){
Element *el = new Element();
el->n1 = n;
el->next = head;
head = el;
}
__device__ __host__ Node popFirstNode(){
Element *cur = head;
Node n;
if(cur != NULL){
n = cur -> n1;
head = head -> next;
}
delete cur;
return n;
}
__device__ __host__ bool isEmpty(){
Element *cur = head;
if(cur == NULL){
return true;
}
return false;
}
Element *head;
};
//LISTS
__global__ void listsKernel(LinkedList* d_Results, int numLists){
int idx = blockIdx.x * blockDim.x + threadIdx.x;
Node n(1,1);
if(idx < numLists){
d_Results[idx].addNode(n);
d_Results[idx].addNode(n);
d_Results[idx].addNode(n);
d_Results[idx].addNode(n);
}
}
int main(){
int numLists = 10;
size_t size = numLists * sizeof(LinkedList);
LinkedList curList;
LinkedList* h_Results = (LinkedList*)malloc(size);
LinkedList* d_Results;
cudaMalloc((void**)&d_Results, size);
listsKernel<<<256,256>>>(d_Results, numLists);
cudaMemcpy(h_Results, d_Results, sizeof(LinkedList)*numLists, cudaMemcpyDeviceToHost);
for(int i = 0; i < numLists; i++){
curList = h_Results[i];
while(curList.isEmpty() == false){
Node n = curList.popFirstNode();
std::cout << "x: " << n.get_row() << " y: " << n.get_col();
}
}
}
As you can see I'm trying to populate 10 linked lists on the device and then return them back to the host, but the code above results in unhandled exception - Access violation reading location. I am assuming it is not coping the pointers from the device.
Any help would be great.
Just eyeballing the code, it seems you have a fundamental misconception: there is host memory which cannot be accessed from the device, and device memory which cannot be accessed from the host. So when you create linked list nodes in device memory and copy the pointers back to the host, the host cannot dereference those pointers, because they are pointing to device memory.
If you truly want to pass linked lists back and forth between host and device, your best bet is probably to copy the entries into an array, do the memcpy, then copy the array back into a linked list. Other things can be done too, depending on just what your use case is.
(it is possible to allocate a region of memory that is accessible both from the host and from the device, but there is some awkwardness with it and I have no experience using it)

Memory allocation of struct in C++

My struct is as follows:
typedef struct KeypointSt {
float row, col;
float scale, ori;
unsigned char *descrip; /* Vector of descriptor values */
struct KeypointSt *next;
} *Keypoint;
The following is a part of a code in C. How can I translate it to C++, considering allocation and de-allocation of heap.
Keypoint k, keys = NULL;
for (i = 0; i < num; i++) {
/* Allocate memory for the keypoint. */
k = (Keypoint) malloc(sizeof(struct KeypointSt));
k->next = keys;
keys = k;
k->descrip = malloc(len);
for (j = 0; j < len; j++) {
k->descrip[j] = (unsigned char) val;
}
}
One possible way of converting to C++ is:
#include <cstring> // memset()
typedef struct KeypointSt
{
float row, col;
float scale, ori;
size_t len;
unsigned char *descrip; /* Vector of descriptor values */
KeypointSt *next;
KeypointSt(int p_len, int p_val) : row(0.0), col(0.0), scale(0.0),
ori(0.0), len(p_len),
descrip(new unsigned char[len]), next(0)
{ memset(descrip, len, p_val); }
~KeypointSt() { delete descrip; }
} *Keypoint;
extern KeypointSt *init_keypoints(size_t num, size_t len, unsigned char val);
extern void free_keypoints(KeypointSt *list);
KeypointSt *init_keypoints(size_t num, size_t len, unsigned char val)
{
KeypointSt *keys = NULL;
for (size_t i = 0; i < num; i++)
{
/* Allocate memory for the keypoint. */
KeypointSt *k = new KeypointSt(len, val);
k->next = keys;
keys = k;
}
return keys;
}
void free_keypoints(KeypointSt *list)
{
while (list != 0)
{
KeypointSt *next = list->next;
delete list;
list = next;
}
}
int main(void)
{
KeypointSt *keys = init_keypoints(4, 5, 6);
free_keypoints(keys);
return 0;
}
The only reason I've kept the typedef in place is because you have existing code; the C++ code would be better using KeypointSt * everywhere — or renaming the structure tag to Keypoint and using Keypoint * in place of your original Keypoint. I don't like non-opaque types where the typedef conceals a pointer. If I see a declaration XYZ xyz;, and it is a structure or class type, I expect to use xyz.pqr and not xyz->pqr.
We can debate code layout of the constructor code, the absence of a default constructor (no arrays), and the absence of a copy constructor and an assignment operator (both needed because of the allocation for descrip). The code of init_keypoints() is not exception safe; a memory allocation failure will leak memory. Fixing that is left as an exercise (it isn't very hard, I think, but I don't claim exception-handling expertise). I've not attempted to consider any extra requirements imposed by C++11. Simply translating from C to C++ is 'easy' until you look at the extra demands that C++ makes — demands that make your life easier in the long run, but at a short-term cost in pain.

visual c++: convert int into string pointer

how to convert integer into string pointer in visual c++?
Use stringstream
#include <sstream>
stringstream ss;
ss << i;
string s = ss.str();
If you using CString, then you can use Format() method like this:
int val = 489;
CString s;
s.Format("%d", val);
search for atoi / itoa in your favorite documentation. Or try Boost (www.boost.org - library Conversion, lexical_cast).
Both ways are portable across different compilers.
There is a very easy method
int i=4;
String ^ s = Convert::ToString(i);
If you want a textual representation of the pointer address use sprintf.
If you want to treat the numeric value as a pointer to a string use casting like so:
int intValue = ...;
char * charPtr = (char*)intValue;
Take any C and C++ textbook. This simple C code should work in Visual C++ and others C++ compilels and convert 489 into "489":
char result[100];
int num = 489;
sprintf(result, "%d", num);
basic C++
char text[100];
int num=123;
itoa(num,text,10);
This is how I did it in my homework since we were only allowed to use some predetermined libraries. I'm pretty sure it's not considered a "best practice" though ;)
string int2string(int integer) {
string str;
int division = integer;
while (division > 0) {
str = char('0' + (division % 10)) + str;
division = division / 10;
}
return str;
}
I think the easiest one would be:
int i;
String s=i.toString();
// It is about Visual C++
You got homework? a generic one, tested if g++, http://effocore.googlecode.com/svn/trunk/devel/effo/codebase/addons/inl/include/impl/algo_impl.h
:
#ifdef __cplusplus
static inline char *int2a_put(uintptr_t i, char *s)
{
do {
*s++ = '0' + i % 10;
i /= 10;
} while (i);
return s;
}
static inline void int2a_reverse(char *head, char *tail)
{
for (*tail = '\0'; --tail > head; ++head) {
/* exchange */
(*head) ^= (*tail);
(*tail) ^= (*head);
(*head) ^= (*tail);
}
}
template<typename t>
static inline const char *int2a(t i, char *s)
{
char *p;
char *ret = s;
bool f = false;
p = s;
if (i < 0) {
*p++ = '-';
++ s;
/*
* In limits.h, INT_MAX was defined as
* maximum values a `signed int' can hold.
* and LONG_MAX was defined as maximum values
* a `signed long int' can hold.
*/
switch (sizeof(t)) {
case 8:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
ef64_t a = (ef64_t)i;
if (-LLONG_MAX > a) {
i = (t)LLONG_MAX;
f = true;
}
}
break;
case 4:
case 2:
case 1:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
int a = (int)i;
if (-INT_MAX > a) {
i = (t)INT_MAX;
f = true;
}
}
break;
default:
break;
}
if (!f) {
i = -i;
}
}
p = int2a_put((uintptr_t)i, p);
if (f) {
++ *s;
}
int2a_reverse(s, p);
return ret;
}
/*
* No "static" otherwise g++ complains
* "explicit template specialization cannot have a storage class"
*/
template<>
/*static*/ inline
const char *int2a<uintptr_t>(uintptr_t i, char *s)
{
char *p = int2a_put(i, s);
int2a_reverse(s, p);
return s;
}
#else

Resources