Exception thrown: read access violation. this->pt_mat was 0x1110112 - visual-c++

I got this error while using a double pointer in a class function to set coefficient and using it in the main.
The class function is used in a stand-alone function to set the coefficient using a class type pointer.
The class code is:
class Matrix
{
private:
int size_m, size_n;
double **pt_mat;
public:
Matrix() {};
Matrix(int m, int n)
{
pt_mat = new double *[m];
for (int i = 0; i < m; i++)
{
pt_mat[i] = new double[n];
}
}
void set_size(int m, int n)
{
size_m = m;
size_n = n;
}
void set_coef(int i, int j, double x)
{
pt_mat[i][j] = x;
}
void get_size(int *pt_m, int *pt_n)
{
*pt_m = size_m;
*pt_n = size_n;
}
double get_coef(int i, int j)
{
return pt_mat[i][j];
}
void print(ofstream &fout)
{
fout << size_m << " " << size_n << endl;
int i, j;
for (i = 0; i < size_m; i++)
{
for (j = 0; j < size_n; j++)
{
fout << pt_mat[i][j] << " ";
}
fout << endl;
}
}
void max_min(int *pt_imax, int *pt_jmax, double *pt_max, int *pt_imin, int *pt_jmin, double *pt_min)
{
double max, min;
int i, j, imax = 0, imin = 0, jmax = 0, jmin = 0;
max = pt_mat[0][0];
for (i = 0; i < size_m; i++)
{
for (j = 0; j < size_n; j++)
{
if (pt_mat[i][j] > max)
{
max = pt_mat[i][j];
imax = i;
jmax = j;
}
}
}
*pt_max = max;
*pt_imax = imax;
*pt_jmax = jmax;
min = pt_mat[0][0];
for (i = 0; i < size_m; i++)
{
for (j = 0; j < size_n; j++)
{
if (pt_mat[i][j] < min)
{
min = pt_mat[i][j];
imin = i;
jmin = j;
}
}
}
*pt_min = min;
*pt_imin = imin;
*pt_jmin = jmin;
}
};
The stand-alone function:
void mat_add(Matrix a, Matrix b, Matrix *pt_c)
{
Matrix c;
pt_c = &c;
int a_m, a_n, *p_am = &a_m, *p_an = &a_n;
a.get_size(p_am, p_an);
c.set_size(a_m, a_n);
int m, n, *pt_m = &m, *pt_n = &n;
double coef;
a.get_size(pt_m, pt_n);
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
{
coef = a.get_coef(i, j) + b.get_coef(i, j);
c.set_coef(i, j, coef);
}
}
please help me in this regard if you can. I have no syntax error showing.enter code here

Related

missing template arguments before '[' token

I am very new in R and cpp. These are my cpp codes with Rcpp.
#include <cmath>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector getPerformance(NumericVector accProfitSeries, NumericVector dateSeries, double capital, double riskFreeRate)
{
NumericVector retult(8);
int Length = accProfitSeries.length();
double strategyProfit = accProfitSeries[Length - 1];
double returnRate = log(strategyProfit / capital);
double tradingPeriod = (dateSeries[dateSeries.length() - 1] - dateSeries[0]) / 365;
double returnRateYear = returnRate / tradingPeriod;
double sharpeRatio;
for (int i = 0; i < 8; i++) {
result[i] = 0;
}
NumericVector capitalLevel(Length), capitalReturn(Length);
double meanReturn, sumReturn, stdReturn;
double tmp;
for (int i = 0; i < Length; i++)
{
capitalLevel[i] = accProfitSeries[i] + capital;
capitalReturn[i] = log(capitalReturn[i] / capitalReturn[0]);
sumReturn = sumReturn + capitalReturn[i];
}
meanReturn = sumReturn / Length;
for (int i = 0; i < Length; i++)
tmp += pow(capitalReturn[i] - meanReturn, 2);
stdReturn = sqrt(tmp / Length);
sharpeRatio = (meanReturn - riskFreeRate) / stdReturn;
double maxCapital = 0, drawback = 0, maxDrawback = 0, maxDrawbackPercent = 0;
int drawbackPeriod = 0, maxDrawbackPeriod = 0;
for (int i = 0; i < Length; i++)
{
maxCapital = max(NumericVector::create(maxCapital, capitalLevel[i]));
drawback = capitalLevel[i] - maxCapital;
maxDrawback = min(NumericVector::create(maxDrawback, drawback));
maxDrawbackPercent = maxDrawback / (maxCapital - capital);
if (drawback >= 0)
{
drawbackPeriod = 0;
}
else
{
drawbackPeriod++;
maxDrawbackPeriod = max(NumericVector::create(maxDrawbackPeriod, drawbackPeriod));
}
}
result[0] = returnRate;
result[1] = tradingPeriod;
result[2] = returnRateYear;
result[3] = sharpeRatio;
result[4] = maxDrawback;
result[5] = maxDrawbackPeriod;
result[6] = strategyProfit;
result[7] = maxDrawbackPercent;
return(result);
}
I got one of the error messages, others are similar:
getPerformance.cpp:17:9: error: missing template arguments before '[' token
result[i] = 0;
How do I solve it?
Mainly, you have two issues:
As pointed out by #DirkEddelbuettel, you need to change retult(8) to result(8) to proper setup a variable referenced elsewhere in the script.
You failed to initialize several double variables.
The following should work...
#include <cmath>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector getPerformance(NumericVector accProfitSeries,
NumericVector dateSeries,
double capital, double riskFreeRate)
{
NumericVector result(8); // retult -> result
int Length = accProfitSeries.length();
double strategyProfit = accProfitSeries[Length - 1];
double returnRate = log(strategyProfit / capital);
double tradingPeriod = (dateSeries[dateSeries.length() - 1] - dateSeries[0]) / 365;
double returnRateYear = returnRate / tradingPeriod;
double sharpeRatio = 0.0; // Initialize value
for (int i = 0; i < 8; i++) {
result[i] = 0;
}
NumericVector capitalLevel(Length), capitalReturn(Length);
// Initialize values
double meanReturn = 0.0, sumReturn = 0.0, stdReturn = 0.0;
double tmp = 0.0;
for (int i = 0; i < Length; i++) {
capitalLevel[i] = accProfitSeries[i] + capital;
capitalReturn[i] = log(capitalReturn[i] / capitalReturn[0]);
sumReturn = sumReturn + capitalReturn[i];
}
meanReturn = sumReturn / Length;
for (int i = 0; i < Length; i++)
tmp += pow(capitalReturn[i] - meanReturn, 2);
stdReturn = sqrt(tmp / Length);
sharpeRatio = (meanReturn - riskFreeRate) / stdReturn;
double maxCapital = 0, drawback = 0, maxDrawback = 0, maxDrawbackPercent = 0;
int drawbackPeriod = 0, maxDrawbackPeriod = 0;
for (int i = 0; i < Length; i++) {
maxCapital = max(NumericVector::create(maxCapital, capitalLevel[i]));
drawback = capitalLevel[i] - maxCapital;
maxDrawback = min(NumericVector::create(maxDrawback, drawback));
maxDrawbackPercent = maxDrawback / (maxCapital - capital);
if (drawback >= 0) {
drawbackPeriod = 0;
} else {
drawbackPeriod++;
maxDrawbackPeriod = max(NumericVector::create(maxDrawbackPeriod, drawbackPeriod));
}
}
result[0] = returnRate;
result[1] = tradingPeriod;
result[2] = returnRateYear;
result[3] = sharpeRatio;
result[4] = maxDrawback;
result[5] = maxDrawbackPeriod;
result[6] = strategyProfit;
result[7] = maxDrawbackPercent;
return(result);
}

C++ Console Application1.exe has triggered a breakpoint,Visual Studio 2015.Array and random numbers

I'm trying to run this code in VS 2015 c++, but I have this problem: while getting the correct answer, I also get the error C++ Console Application1.exe has triggered a breakpoint. My task is to randomly choose 10 numbers between 1 and 50, show these numbers and sort them by odd and even numbers. Thanks in advance.
#include<iostream>
#include<ctime>
using namespace std;
void main() {
const int size = 10;
srand(time(NULL));
int arr[size], odd = 0, even = 0;
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 50 + 1;
cout << arr[i] << '\t';
}
cout << endl;
int *arrOdd = new int[odd];
int *arrEven = new int[even];
for (int i = 0; i < size; i++)
{
if (arr[i] % 2 == 0) {
arrEven[even] = arr[i];
even++;
}
else
{
arrOdd[odd] = arr[i];
odd++;
}
}
int a = 0, b = 0;
for (int i = 0; i < size; i++)
if (arr[i] % 2 == 0) {
cout << "arrEven = " << arrEven[a] << endl;
a++;
}
else
{
cout << "arrOdd = " << arrOdd[b] << endl;
b++;
}
system("pause");
}
int arr[size], odd = 0, even = 0;
//odd's and event's dont change
//...
int *arrOdd = new int[odd];
int *arrEven = new int[even];
So you are trying to allocate arrays with 0 length

Matrix multiplication with threads and semaphore

I have to implement matrix multiplication with threads using semaphore. The problem is I don't understand how semaphore works and my result matrix is filled with zeros and program hangs. Could you explain me what I'm doing wrong?
Here's my code:
class Program
{
private static Semaphore semaphore = new Semaphore(0, 1);
static void Main(string[] args)
{
int size;
int[,] a = null, b = null, c = null;
bool isNumeric;
do
{
Console.Write("Insert size: ");
isNumeric = int.TryParse(Console.ReadLine(), out size);
}
while (!isNumeric || size < 2);
Console.WriteLine();
SquareMatrix.Init(size, ref a);
SquareMatrix.Init(size, ref b);
SquareMatrix.Init(size, ref c);
SquareMatrix.Fill(a);
SquareMatrix.Fill(b);
Console.WriteLine("Matrix 1:\n");
SquareMatrix.Display(a);
Console.WriteLine("Matrix 2:\n");
SquareMatrix.Display(b);
Console.WriteLine();
DateTime start = DateTime.Now;
for (int i = 0; i < size; i++)
{
Thread thread = new Thread(() => Multiply(i, size, a, b, c));
thread.Name = i.ToString();
thread.Start();
}
DateTime stop = DateTime.Now;
Console.WriteLine("Result (" + (stop - start).TotalMilliseconds + " ms):\n");
SquareMatrix.Display(c);
Console.ReadLine();
}
public static void Multiply(int i, int size, int[,] a, int[,] b, int[,] c)
{
semaphore.WaitOne();
for (int j = 0; j < size; j++)
{
c[i, j] = 0;
for (int k = 0; k < size; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
semaphore.Release();
}
}
And SquareMatrix code:
static class SquareMatrix
{
private static readonly Random random = new Random();
public static void Init(int size, ref int[,] array)
{
array = new int[size, size];
}
public static void Fill(int[,] array)
{
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
array[i, j] = random.Next(-10, 10);
}
}
}
public static void Display(int[,] array)
{
string result = "";
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
result += array[i, j] + " ";
result += "\n";
}
Console.Write(result + "\n");
}
}

Find the word in the stream?

Given an infinite stream of characters and a list L of strings, create a function that calls an external API when a word in L is recognized during the processing of the stream.
Example:
L = ["ok","test","one","try","trying"]
stream = a,b,c,o,k,d,e,f,t,r,y,i,n,g.............
The call to external API will happen when 'k' is encountered, again when the 'y' is encountered, and again at 'g'.
My idea:
Create trie out of the list and navigate the nodes as you read from stream in linear time. But there would be a bug if you just do simple trie search.
Assume you have words "abxyz" and "xyw" and your input is "abxyw".In this case you can't recognize "xyw" with trie.
So search should be modified as below:
let's take above use case "abxyw". We start the search and we find we have all the element till 'x'. Moment you get 'x' you have two options:
Check if the current element is equal to the head of trie and if it is equal to head of trie then call recursive search.
Continue till the end of current word. In this case for your given input it will return false but for the recursive search we started in point 1, it will return true.
Below is my modified search but I think it has bugs and can be improved. Any suggestions?
#define SIZE 26
struct tri{
int complete;
struct tri *child[SIZE];
};
void insert(char *c, struct tri **t)
{
struct tri *current = *t;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
if(current->child[letter] == NULL) {
current->child[letter] = malloc(sizeof(*current));
memset(current->child[letter], 0, sizeof(struct tri));
}
current = current->child[letter];
c++;
}
current->complete = 1;
}
struct tri *t;
int flag = 0;
int found(char *c, struct tri *tt)
{
struct tri *current = tt;
if (current == NULL)
return 0;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
/* if this is the first char then recurse from begining*/
if (t->child[letter] != NULL)
flag = found(c+1, t->child[letter]);
if (flag == 1)
return 1;
if(!flag && current->child[letter] == NULL) {
return 0;
}
current = current->child[letter];
c++;
}
return current->complete;
}
int main()
{
int i;
t = malloc(sizeof(*t));
t->complete = 0;
memset(t, 0, sizeof(struct tri));
insert("weathez", &t);
insert("eather", &t);
insert("weather", &t);
(1 ==found("weather", t))?printf("found\n"):printf("not found\n");
return 0;
}
What you want to do is exactly what Aho-Corasick algorithm does.
You can take a look at my Aho-Corasick implementation. It's contest-oriented, so maybe not focused on readability but I think it's quite clear:
typedef vector<int> VI;
struct Node {
int size;
Node *fail, *output;
VI id;
map<char, Node*> next;
};
typedef pair<Node*, Node*> P;
typedef map<char, Node*> MCP;
Node* root;
inline void init() {
root = new Node;
root->size = 0;
root->output = root->fail = NULL;
}
Node* add(string& s, int u, int c = 0, Node* p = root) {
if (p == NULL) {
p = new Node;
p->size = c;
p->fail = p->output = NULL;
}
if (c == s.size()) p->id.push_back(u);
else {
if (not p->next.count(s[c])) p->next[s[c]] = NULL;
p->next[s[c]] = add(s, u, c + 1, p->next[s[c]]);
}
return p;
}
void fill_fail_output() {
queue<pair<char, P> > Q;
for (MCP::iterator it=root->next.begin();
it!=root->next.end();++it)
Q.push(pair<char, P> (it->first, P(root, it->second)));
while (not Q.empty()) {
Node *pare = Q.front().second.first;
Node *fill = Q.front().second.second;
char c = Q.front().first; Q.pop();
while (pare != root && !pare->fail->next.count(c))
pare=pare->fail;
if (pare == root) fill->fail = root;
else fill->fail = pare->fail->next[c];
if (fill->fail->id.size() != 0)
fill->output = fill->fail;
else fill->output = fill->fail->output;
for (MCP::iterator it=fill->next.begin();
it!=fill->next.end();++it)
Q.push(pair<char,P>(it->first,P(fill,it->second)));
}
}
void match(int c, VI& id) {
for (int i = 0; i < id.size(); ++i) {
cout << "Matching of pattern " << id[i];
cout << " ended at " << c << endl;
}
}
void search(string& s) {
int i = 0, j = 0;
Node *p = root, *q;
while (j < s.size()) {
while (p->next.count(s[j])) {
p = p->next[s[j++]];
if (p->id.size() != 0) match(j - 1, p->id);
q = p->output;
while (q != NULL) {
match(j - 1, q->id);
q = q->output;
}
}
if (p != root) {
p = p->fail;
i = j - p->size;
}
else i = ++j;
}
}
void erase(Node* p = root) {
for (MCP::iterator it = p->next.begin();
it != p->next.end(); ++it)
erase(it->second);
delete p;
}
int main() {
init();
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
add(s, i);
}
fill_fail_output();
string text;
cin >> text;
search(text);
erase(root);
}

char in string is not in order wanted

I am a beginner and I need some help here. This program prints out the frequency of char in the string, e.g. if user enters zzaaa it prints out a3z2 and what I need to print is z2a3 since z is entered first before a. But I am having a hard time switching the order around. Thanks in advance!
int main
{
int ib, i=0, j=0, k=0;
int count[26] = {0};
char chh[3][10];
for (ib = 0; ib < 3; ib++) // get 3 input
gets(chh[ib]);
for (i = 0; i < 3; i++)
{
for (j = 0; j < 10; j++)
{
if (chh[i][j] >= 'a' && chh[i][j] <= 'z')
{
count[chh[i][j] - 'a']++;
}
}
for (k = 0; k < 26; k++)
{
if (count[k] != 0) // if array location is not equals to 0
printf("%c%d", k + 'a', count[k]);
}
memset(count, 0, sizeof(count)); //reset integer array
printf("\n");
}
It prints a before z because you arranged count from a to z by alphabetic priority not entering priority:
count[chh[i][j] - 'a']
if you want to print them by entering priority you should change it. there are several ways to do this. like this:
#include <stdio.h>
#include <string.h>
int main()
{
int ib, i=0, j=0,k=0, kk=0,c=0,found=0;
int count[26][2];
char chh[3][10];
for (ib = 0; ib < 3; ib++) // get 3 input
gets(chh[ib]);
printf("output is:\n");
for (i=0;i<26;i++)
{
count[i][0]=0;
count[i][1]=0;
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 10; j++)
{
if (chh[i][j] >= 'a' && chh[i][j] <= 'z')
{
found=0;
for (c=0;c<kk;c++)
if (count[c][0]==chh[i][j])
{
count[c][1]++;
found=1;
break;
}
if (!found)
{
count[c][0]=chh[i][j];
count[c][1]++;
kk++;
}
}
}
for (k = 0; k < 26; k++)
{
if (count[k][1] != 0) // if array location is not equals to 0
printf("%c%d", count[k][0], count[k][1]);
}
memset(count, 0, sizeof(count)); //reset integer array
printf("\n");
}
}

Resources