Create variable amount of struct objects inside a struct (C) - c

I haven't written any C for more than a decade, but here I am...
I want to be able to create and access the following items of a data structure:
FilterCoefficients[0].TargetSampleNum = 0;
FilterCoefficients[0].SourceWeights[0].Weight = 0.812;
FilterCoefficients[0].SourceWeights[0].SourceSampleNum = 0;
FilterCoefficients[0].SourceWeights[1].Weight = 0.153;
FilterCoefficients[0].SourceWeights[1].SourceSampleNum = 1;
FilterCoefficients[1].TargetSampleNum = 1;
FilterCoefficients[1].SourceWeights[0].Weight = 0.352;
FilterCoefficients[1].SourceWeights[0].SourceSampleNum = 0;
FilterCoefficients[1].SourceWeights[1].Weight = 0.721;
FilterCoefficients[1].SourceWeights[1].SourceSampleNum = 1;
[...]
The indices have to be dynamically allocated (amount of needed space changes during runtime). I am attempting to create said data structure with the following:
typedef struct SampleWeight_t
{
unsigned long SourceSampleNum;
double Weight;
} SampleWeight;
typedef struct FilterCoefficients_t
{
unsigned long TargetSampleNum;
SampleWeight* SourceWeights;
} FilterCoefficients;
However, I am having difficulties creating the structure. I am getting Break Point exceptions when malloc-ing or free-ing the structure.
FilterCoefficients* FilterCoefficients;
SampleWeight* SampleWeight;
FilterCoefficients = malloc(sizeof(FilterCoefficients) * target_width);
if (FilterCoefficients == NULL) {
//errhandler
}
for (int i = 0; i < target_width; i++) {
FilterCoefficients[i].SourceWeights = malloc(sizeof(SampleWeight) * (int)ceil(scalingFactorWidth * window_width)); // **exception usually here**
if (FilterCoefficients[i].SourceWeights == NULL) {
//errhandler
}
FilterCoefficients[i].TargetSampleNum = i;
for (int j = i - filter_width; j < i + filter_width; j++) {
FilterCoefficients[i].SourceWeights[j + filter_width].Weight = bilinear_filter(0.5 + scalingFactorWidth2 * (j - 0.5));
if (j > 0) {
FilterCoefficients[i].SourceWeights[j + filter_width].SourceSampleNum = j;
}
else {
FilterCoefficients[i].SourceWeights[j + filter_width].SourceSampleNum = 0;
}
}
}
for (int i = 0; i < target_width; i++) {
free(FilterCoefficients[i].SourceWeights); // **exception usually here**
}
free(FilterCoefficients);
Any help which is gonna point me to a solution is appreciated.

This compiles and executes. I had to simplify.
#include <stdio.h>
#include <stdlib.h>
typedef struct SampleWeight_t
{
unsigned long SourceSampleNum;
double Weight;
} SampleWeight;
typedef struct FilterCoefficients_t
{
unsigned long TargetSampleNum;
SampleWeight* SourceWeights;
} FilterCoefficients;
int main ( void) {
FilterCoefficients* FilterCoeff;
int window_width = 35;
int target_width = 55;
FilterCoeff = malloc(sizeof(FilterCoefficients) * target_width);
if (FilterCoeff == NULL) {
//errhandler
}
for (int i = 0; i < target_width; i++) {
FilterCoeff[i].SourceWeights = malloc(sizeof(SampleWeight) * window_width);
if (FilterCoeff[i].SourceWeights == NULL) {
//errhandler
}
FilterCoeff[i].TargetSampleNum = i;
for (int j = 0; j < window_width; j++) {
FilterCoeff[i].SourceWeights[j].Weight = i * j;
if (j > 0) {
FilterCoeff[i].SourceWeights[j].SourceSampleNum = j;
}
else {
FilterCoeff[i].SourceWeights[j].SourceSampleNum = 0;
}
}
}
for (int i = 0; i < target_width; i++) {
free(FilterCoeff[i].SourceWeights); // **exception usually here**
}
free(FilterCoeff);
}

Related

Segfault in Merge - Sort in C

I am trying to sort an array of structures of size 5500 using merge sort.
However, I am getting a segmentation fault pretty quickly because I am not allowed to use VLA. so I have to create 2 extra arrays of size 5500 each time I call merge-sort recursively.
I would appreciate a fix for my problem. I will provide my code here:
void merge(Student rightArr[], Student leftArr[], Student mergedArr[], int sizeOfRight, int sizeOfLeft) {
int rightArrIndex = 0;
int leftArrIndex = 0;
int mergedArrIndex = 0;
while (leftArrIndex < sizeOfLeft && rightArrIndex < sizeOfRight) {
char *ptrLeft, *ptrRight;
long gradeLeft = strtol(leftArr[leftArrIndex].grade, &ptrLeft, BASE_COUNT);
long gradeRight = strtol(rightArr[rightArrIndex].grade, &ptrRight, BASE_COUNT);
if (gradeLeft > gradeRight) {
mergedArr[mergedArrIndex] = rightArr[rightArrIndex];
rightArrIndex++;
} else {
mergedArr[mergedArrIndex] = leftArr[leftArrIndex];
leftArrIndex++;
}
mergedArrIndex++;
}
if (leftArrIndex == sizeOfLeft) {
for (int i = mergedArrIndex; i < (sizeOfLeft + sizeOfRight); i++) {
mergedArr[i] = rightArr[rightArrIndex];
rightArr++;
}
} else {
for (int i = mergedArrIndex; i < (sizeOfLeft + sizeOfRight); i++) {
mergedArr[i] = leftArr[leftArrIndex];
leftArr++;
}
}
}
void mergeSort(Student studentsArray[], int amountOfStudents) {
if (amountOfStudents <= 1) {
return;
}
int leftSize = (amountOfStudents / 2);
int rightSize = (amountOfStudents - leftSize);
Student leftArr[5500], rightArr[5500];
for (int i = 0; i < leftSize; i++) {
leftArr[i] = studentsArray[i];
}
for (int i = 0; i < rightSize; i++) {
rightArr[i] = studentsArray[i + leftSize];
}
mergeSort(leftArr, leftSize);
mergeSort(rightArr, rightSize);
merge(rightArr, leftArr, studentsArray, rightSize, leftSize);
}
Ok, I think this should do what you want. It assumes that Student and BASE_COUNT have been defined:
#include <stdlib.h>
#include <stdio.h>
void merge(Student studentsArr[],
int leftSize, int rightSize,
Student scratchArr[])
{
Student *leftArr = studentsArr;
Student *rightArr = studentsArr + leftSize;
int leftIx = 0, rightIx = 0, mergeIx = 0, ix;
while (leftIx < leftSize && rightIx < rightSize) {
long gradeLeft = strtol(leftArr[leftIx].grade, NULL, BASE_COUNT);
long gradeRight = strtol(rightArr[rightIx].grade, NULL, BASE_COUNT);
if (gradeLeft <= gradeRight) {
scratchArr[mergeIx++] = leftArr[leftIx++];
}
else {
scratchArr[mergeIx++] = rightArr[rightIx++];
}
}
while (leftIx < leftSize) {
scratchArr[mergeIx++] = leftArr[leftIx++];
}
// Copy the merged values from scratchArr back to studentsArr.
// The remaining values from rightArr (if any) are already in
// their proper place at the end of studentsArr, so we stop
// copying when we reach that point.
for (ix = 0; ix < mergeIx; ix++) {
studentsArr[ix] = scratchArr[ix];
}
}
void mergeSortInternal(Student studentsArray[],
int amountOfStudents,
Student scratchArr[])
{
if (amountOfStudents <= 1) {
return;
}
int leftSize = amountOfStudents / 2;
int rightSize = amountOfStudents - leftSize;
mergeSortInternal(studentsArray, leftSize, scratchArr);
mergeSortInternal(studentsArray + leftSize, rightSize, scratchArr);
merge(studentsArray, leftSize, rightSize, scratchArr);
}
#define MAX_ARR_SIZE 5500
void mergeSort(Student studentsArray[], int amountOfStudents)
{
if (amountOfStudents <= 1) {
return;
}
if (amountOfStudents > MAX_ARR_SIZE) {
fprintf(stderr, "Array too large to sort.\n");
return;
}
Student scratchArr[MAX_ARR_SIZE];
mergeSortInternal(studentsArray, amountOfStudents, scratchArr);
}
The top-level sort function is mergeSort, defined as in the original post. It declares a single scratch array of size MAX_ARR_SIZE, defined as 5500. The top-level function is not itself recursive, so this scratch array is only allocated once.

Pthread: Increasing program execution time with respect to number of threads

I am trying to build an efficient concurrent hash map using pthreads, C.
Following is my implementation
#include <stdlib.h>
#include <stddef.h>
#include <pthread.h>
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#include <linux/limits.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#define ENTRIES_PER_BUCKET 3
struct Bucket
{
pthread_mutex_t mutex;
void **keys;
int *vals;
struct Bucket *next;
};
struct Concurrent_Map
{
struct Bucket *buckets;
map_keys_equality *keys_eq;
map_key_hash *khash;
int capacity;
};
int concurrent_map_allocate /*# <t> #*/ (map_keys_equality *keq, map_key_hash *khash,
unsigned capacity,
struct Concurrent_Map **map_out)
{
struct Concurrent_Map *old_map_val = *map_out;
struct Concurrent_Map *map_alloc = malloc(sizeof(struct Concurrent_Map));
if (map_alloc == NULL)
{
return 0;
}
*map_out = (struct Concurrent_Map *)map_alloc;
struct Bucket *buckets_alloc = (struct Bucket *)malloc(sizeof(struct Bucket) * (int)capacity);
if (buckets_alloc == NULL)
{
free(map_alloc);
*map_out = old_map_val;
return 0;
}
(*map_out)->buckets = buckets_alloc;
(*map_out)->capacity = capacity;
(*map_out)->keys_eq = keq;
(*map_out)->khash = khash;
unsigned i;
for (i = 0; i < capacity; i++)
{
if (pthread_mutex_init(&((*map_out)->buckets[i].mutex), NULL) == 0)
{
void **key_alloc = malloc(sizeof(void *) * (ENTRIES_PER_BUCKET));
if (key_alloc != NULL)
{
(*map_out)->buckets[i].keys = key_alloc;
int k;
for (k = 0; k < ENTRIES_PER_BUCKET; k++)
{
(*map_out)->buckets[i].keys[k] = NULL;
}
}
int *vals_alloc = malloc(sizeof(int) * (ENTRIES_PER_BUCKET));
if (vals_alloc != NULL)
{
(*map_out)->buckets[i].vals = vals_alloc;
int k;
for (k = 0; k < ENTRIES_PER_BUCKET; k++)
{
(*map_out)->buckets[i].vals[k] = -1;
}
}
(*map_out)->buckets[i].next = NULL;
}
}
// todo exceptions in allocation
return 1;
}
static unsigned loop(unsigned k, unsigned capacity)
{
unsigned g = k % capacity;
unsigned res = (g + capacity) % capacity;
return res;
}
int concurrent_map_get(struct Concurrent_Map *map, void *key, int *value_out)
{
map_key_hash *khash = map->khash;
unsigned hash = khash(key);
unsigned start = loop(hash, map->capacity);
unsigned bucket_index = loop(start + 0, map->capacity);
if (bucket_index < map->capacity)
{
struct Bucket *bucket = &(map->buckets[bucket_index]);
pthread_mutex_t mutex = bucket->mutex;
pthread_mutex_lock(&mutex);
int j;
do
{
for (j = 0; j < ENTRIES_PER_BUCKET; j++)
{
int val = bucket->vals[j];
if (map->keys_eq(bucket->keys[j], key))
{
if (bucket->vals[j] == val)
{
*value_out = val;
return 1;
}
else
{
*value_out = -1;
return 0;
}
}
}
if (bucket->next != NULL)
{
bucket = (bucket->next);
}
else
{
break;
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex);
} while (1);
}
*value_out = -1;
return 0;
}
int concurrent_map_put(struct Concurrent_Map *map, void *key, int value)
{
map_key_hash *khash = map->khash;
unsigned hash = khash(key);
unsigned start = loop(hash, map->capacity);
unsigned bucket_index = loop(start + 0, map->capacity);
struct Bucket *bucket = &(map->buckets[bucket_index]);
int j;
do
{
pthread_mutex_t mutex = bucket->mutex;
int j;
pthread_mutex_lock(&mutex);
for (j = 0; j < ENTRIES_PER_BUCKET; j++)
{
if (map->keys_eq(bucket->keys[j], key))
{
pthread_mutex_unlock(&mutex);
return 0;
}
else if (bucket->keys[j] == NULL)
{
bucket->vals[j] = value;
bucket->keys[j] = key;
pthread_mutex_unlock(&mutex);
return 1;
}
}
if (bucket->next == NULL)
{
// allocate a new bucket
struct Bucket *new_bucket = malloc(sizeof(struct Bucket));
if (pthread_mutex_init(&(new_bucket->mutex), NULL) == 0)
{
void **key_alloc = malloc(sizeof(void *) * (ENTRIES_PER_BUCKET));
if (key_alloc != NULL)
{
new_bucket->keys = key_alloc;
int k;
for (k = 0; k < ENTRIES_PER_BUCKET; k++)
{
new_bucket->keys[k] = NULL;
}
}
int *vals_alloc = malloc(sizeof(int) * (ENTRIES_PER_BUCKET));
if (vals_alloc != NULL)
{
new_bucket->vals = vals_alloc;
int k;
for (k = 0; k < ENTRIES_PER_BUCKET; k++)
{
new_bucket->vals[k] = -1;
}
}
bucket->next = new_bucket;
}
}
pthread_mutex_unlock(&mutex);
bucket = bucket->next;
} while (1);
return 0;
}
int concurrent_map_erase(struct Concurrent_Map *map, void *key, void **trash)
{
map_key_hash *khash = map->khash;
unsigned hash = khash(key);
unsigned start = loop(hash, map->capacity);
unsigned bucket_index = loop(start + 0, map->capacity);
struct Bucket *bucket = &(map->buckets[bucket_index]);
int j;
do
{
pthread_mutex_t mutex = bucket->mutex;
int j;
pthread_mutex_lock(&mutex);
for (j = 0; j < ENTRIES_PER_BUCKET; j++)
{
if (map->keys_eq(bucket->keys[j], key))
{
bucket->vals[j] = -1;
bucket->keys[j] = NULL;
pthread_mutex_unlock(&mutex);
return 1;
}
}
pthread_mutex_unlock(&mutex);
if (bucket->next != NULL)
{
bucket = (bucket->next);
}
else
{
break;
}
} while (1);
return 0;
}
int concurrent_map_size(struct Concurrent_Map *map)
{
int num_buckets = 0;
struct Bucket *buckets = map->buckets;
unsigned i;
for (i = 0; i < map->capacity; i++)
{
struct Bucket bucket = buckets[i];
do
{
num_buckets++;
if (bucket.next != NULL)
{
bucket = *(bucket.next);
}
else
{
break;
}
} while (1);
}
return num_buckets * ENTRIES_PER_BUCKET;
}
struct FlowId
{
int src_port;
int dst_port;
int src_ip;
int dst_ip;
int internal_device;
int protocol;
};
bool FlowId_eq(void *a, void *b)
{
if (a == NULL || b == NULL)
{
return false;
}
struct FlowId *id1 = a;
struct FlowId *id2 = b;
return (id1->src_port == id2->src_port) && (id1->dst_port == id2->dst_port) && (id1->src_ip == id2->src_ip) && (id1->dst_ip == id2->dst_ip) && (id1->internal_device == id2->internal_device) && (id1->protocol == id2->protocol);
}
unsigned FlowId_hash(void *obj)
{
struct FlowId *id = obj;
unsigned hash = 0;
hash = __builtin_ia32_crc32si(hash, id->src_port);
hash = __builtin_ia32_crc32si(hash, id->dst_port);
hash = __builtin_ia32_crc32si(hash, id->src_ip);
hash = __builtin_ia32_crc32si(hash, id->dst_ip);
hash = __builtin_ia32_crc32si(hash, id->internal_device);
hash = __builtin_ia32_crc32si(hash, id->protocol);
return hash;
}
struct Concurrent_Map *concurrent_map;
#define NUM_THREADS 2
#define NUM_PACKETS 10000000
void *expirator(void *arg)
{
// printf("Thread started executing\n");
unsigned i = 0;
int error = 0;
unsigned packet_count = NUM_PACKETS / NUM_THREADS;
while (i < packet_count)
{
i++;
struct FlowId *id = malloc(sizeof(struct FlowId));
struct FlowId *id1 = malloc(sizeof(struct FlowId));
id->dst_ip = 1;
id->src_ip = 1;
id->internal_device = 1;
id->protocol = 1;
id->src_port = 1;
id->dst_port = rand() % 65536;
id1->dst_ip = 1;
id1->src_ip = 1;
id1->internal_device = 1;
id1->protocol = 1;
id1->src_port = 1;
id1->dst_port = rand() % 65536;
int external_port = rand() % 65536;
int external;
concurrent_map_erase(concurrent_map, id, NULL);
concurrent_map_put(concurrent_map, id, external_port);
concurrent_map_get(concurrent_map, id, &external);
if (external_port != external)
{
error++;
}
else
{
}
}
return NULL;
}
int main()
{
clock_t begin = clock();
concurrent_map_allocate(FlowId_eq, FlowId_hash, 65536, &(concurrent_map));
pthread_t *threads = malloc(sizeof(pthread_t) * NUM_THREADS);
int i;
for (i = 0; i < NUM_THREADS; i++)
{
if (pthread_create(&threads[i], NULL, expirator, NULL) != 0)
{
printf("Error creating threads");
exit(0);
}
}
for (i = 0; i < NUM_THREADS; i++)
{
if (pthread_join(threads[i], NULL) != 0)
{
printf("Error joining threads");
exit(0);
}
}
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%lf\n", time_spent);
return 0;
}
Here is how to run this program.
gcc concurrent_map.c -o test-concurrent-new -lpthread -msse4.2 -O3
Then I measure the execution time for a fixed workload and following are the time values I observed.
1: 3.29
2: 6.687811
3: 5.88
4: 6.23
5: 6.38
6: 6.52
7: 6.74
8: 6.82
It seems that when the number of threads is increased the execution time increases and remains almost same.
I profiled this code using Mutrace, which looks for mutex contention. It turns out that
No mutex contended according to filtering parameters.
I checked the number of cache misses, and it turned out that number of cache misses are roughly equal when the number of threads is modified.
Why does not the execution time decrease when the number of threads increase?
I am running this on a 32 core machine
rand() is usually not suited for multi threaded execution. Instead use rand_r().
Also use linux time tool for timing the application.
Your workload generation imposes a huge overhead, and I assume it is the bottleneck here, not the concurrent hash map

Dynamic memory C, realloc exception

I am trying to write code using dynamic memory allocation, and facing the problem that when realloc() is called in genPointLinkArray(), the program throws an exception: ConsoleApplication1.exe has triggered a breakpoint.
I am using Visual Studio 15 and running the program in Debug mode.
struct graphPoint
{
point p;
int value;
};
struct graphLink
{
point start;
graphPoint end;
};
graphLink* genPointLink(char map[10][10], point start, graphPoint primaryPoint[22], int *linksNum)
{
graphLink *lin = (graphLink*)0;
(*linksNum) = 0;
for (int i = 0; i < 22; i++)
{
if (!ifWay(map, start, primaryPoint[i].p))
{
(*linksNum)++;
if(*linksNum == 1)
lin = (graphLink*)malloc(sizeof(graphLink));
else
{
lin = (graphLink*)realloc(lin, (*linksNum) * sizeof(graphLink));
}
(lin + (*linksNum - 1))->start = start;
(lin + (*linksNum - 1))->end = primaryPoint[i];
}
}
return lin;
}
graphLink* genPointLinkArray(char map[10][10], graphPoint primaryPoint[22], int *linksNum)
{
graphLink *links = (graphLink*)0, *l;
int currentNum = 0;
*linksNum = 0;
for (int i = 0; i < 22; i++)
{
l = genPointLink(map, primaryPoint[i].p, primaryPoint, &currentNum);
if(currentNum != 0)
if (*linksNum == 0)
links = (graphLink*)calloc(currentNum, sizeof(graphLink));
else
links = (graphLink*)realloc(links, ((currentNum + *linksNum) * sizeof(graphLink)));
*linksNum = *linksNum + currentNum;
for (int i = 0; i < currentNum; i++)
{
links[*linksNum - 1 + i].end = l[i].end;
links[*linksNum - 1 + i].start = l[i].start;
}
}
for (int i = 0; i < *linksNum; i++)
{
printf("(%d ; %d) -> (%d ; %d) : %d\n", links[i].start.x, links[i].start.y, links[i].end.p.x, links[i].end.p.y, links[i].end.value);
}
return links;
}
Your problem is the following part of code
*linksNum = *linksNum + currentNum;
for (int i = 0; i < currentNum; i++)
{
links[*linksNum - 1 + i].end = l[i].end;
links[*linksNum - 1 + i].start = l[i].start;
}
You update the *linksNum before the loop, so inside the loop you are addressing the links "array" out of bound: Undefined Behavior.

Trying to find number of possible paths going through all points exactly once starting at the center of a 5x5 array. Diagonal movement is also allowed

#include <iostream>
using namespace std;
long long int acc = 0;
bool isValid(int x, int y, int m[5][5])
{
if(x > -1 && x < 5 && y > -1 && y < 5 && m[x][y] == 0)
{
return true;
}
else
{
return false;
}
}
void start(int x, int y, int m[5][5],int count)
{
if(isValid(x,y,m))
{
count++;
if(count == 25)
{
acc++;
}
else
{
m[x][y] = 1;
start(x+1,y,m,count);
start(x-1,y,m,count);
start(x,y+1,m,count);
start(x,y-1,m,count);
start(x+1,y+1,m,count);
start(x-1,y-1,m,count);
start(x+1,y-1,m,count);
start(x-1,y+1,m,count);
}
}
}
int main()
{
int map[5][5];
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
map[i][j] = 0;
}
}
start(2,2,map,0);
cout<<acc;
}
or another code which i tried
#include <iostream>
#include <vector>
using namespace std;
long long int acc = 0;
class Point
{
public:
int row;
int column;
int count;
int map[5][5];
};
vector<Point> pts;
bool isValid(Point *b)
{
if(b->column > -1 && b->column <5 && b->row > -1 && b->row < 5 && b->map[b->column][b->row] != 1)
{
return true;
}
else
{
return false;
}
}
void start(vector<Point> A)
{
if(A.size() == 0)
{
cout<<acc;
}
Point *temp = &A.back();
A.pop_back();
if(isValid(temp))
{
temp->map[temp->column][temp->row] = 1;
temp->count = temp->count + 1;
if(temp->count == 25)
{
acc++;
}
else
{
Point *p = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
p->map[i][j] = temp->map[i][j];
}
}
p->column = temp->column + 1;
p->row = temp->row;
p->count = temp->count;
A.push_back(*p);
Point *q = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
q->map[i][j] = temp->map[i][j];
}
}
q->column = temp->column - 1;
q->row = temp->row;
q->count = temp->count;
A.push_back(*q);
Point *r = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
r->map[i][j] = temp->map[i][j];
}
}
r->column = temp->column;
r->row = temp->row + 1;
r->count = temp->count;
A.push_back(*r);
Point *s = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
s->map[i][j] = temp->map[i][j];
}
}
s->column = temp->column;
s->row = temp->row - 1;
s->count = temp->count;
A.push_back(*s);
Point *t = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
t->map[i][j] = temp->map[i][j];
}
}
t->column = temp->column + 1;
t->row = temp->row + 1;
t->count = temp->count;
A.push_back(*t);
Point *u = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
u->map[i][j] = temp->map[i][j];
}
}
u->column = temp->column - 1;
u->row = temp->row - 1;
u->count = temp->count;
A.push_back(*u);
Point *v = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
v->map[i][j] = temp->map[i][j];
}
}
v->column = temp->column + 1;
v->row = temp->row - 1;
v->count = temp->count;
A.push_back(*v);
Point *w = new Point;
for(int i = 0; i < 5; i++)
{
for(int j = 0;j < 5; j++)
{
w->map[i][j] = temp->map[i][j];
}
}
w->column = temp->column - 1;
w->row = temp->row + 1;
w->count = temp->count;
A.push_back(*w);
}
}
cout<<A.size();
start(A);
}
int main()
{
pts.clear();
Point *p = new Point;
p->map[2][2] = 0;
p->column = 2;
p->row = 2;
p->count = 0;
cout<<p<<endl;
pts.push_back(*p);
start(pts);
}
the first runs for about 150 iterations and then outputs 0, to indicate no completepaths, which is definitely wrong.
the second seems an error in pointers and addresses, which i still cannot get my head around.

Having issues with pointers

I'm fairly new to programming and i'm having problem with pointers. My code below works with the exception for that my counts doesn't follow with my article number when i sort it. I probably need pointers to get this working but I don't know how.
Can anyone help me?
void printMenu(void)
{
printf("\nMENU:\n");
printf("(D)isplay the menu\n");
printf("(G)enerate inventory\n");
printf("(P)rint inventory\n");
printf("(L)inear search article\n");
printf("(B)inary search article\n");
printf("(I)nsertion sort inventory\n");
printf("B(u)bble sort inventory\n");
printf("(M)erge sort inventory\n");
printf("(Q)uit program\n");
}
void generateInventory(article inventory[], int noOfArticles,
int minArticleNumber, int maxArticleNumber, int maxNoOfArticles)
{
int i, j;
int idCount[] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
for (i = 0; i < noOfArticles; i++)
{
inventory[i].id = rand() % (maxArticleNumber - minArticleNumber + 1) +
minArticleNumber;
idCount[inventory[i].id - 1] = idCount[inventory[i].id - 1] + 1;
for (j = 0; j <= i; ++j)
{
if (idCount[inventory[i].id - 1] > 1)
{
inventory[i].id = rand() % (maxArticleNumber + minArticleNumber);
}
}
inventory[i].counts = rand() % maxNoOfArticles;
}
}
void printInventory(const article inventory[], int noOfArticles)
{
int i;
printf("\nINVENTORY\n");
printf("%7s %8s\n", "Article", "Count");
for (i = 0; i < noOfArticles; i++)
{
printf("%7d %8d\n", inventory[i].id, inventory[i].counts);
}
}
int getArticleId()
{
int id;
printf("\nGive article id: ");
scanf("%d", &id);
return id;
}
void printSearchResult(const article inventory[], int index)
{
if (index == -1)
{
printf("\nArticle not found\n");
}
else
{
printf("\nArticle id: %d\n", inventory[index].id);
printf("Article counts: %d\n", inventory[index].counts);
}
}
int linearSearchInventory(const article inventory[], int noOfArticles, int id)
{
int i = 0;
int index = -1;
while (index == -1 && i < noOfArticles)
{
if (id == inventory[i].id)
{
index = i;
}
i++;
}
}
int binarySearchInventory(const article inventory[], int noOfArticles, int id)
{
int index = -1;
int left = 0;
int right = noOfArticles - 1;
int middle;
while (index == -1 && left <= right)
{
middle = (left + right) / 2;
if (id == inventory[middle].id)
{
index = middle;
}
else if (id < inventory[middle].id)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return index;
}
void insertionSortInventory(article inventory[], int noOfArticles)
{
int i, j;
int next;
for (i = 1; i < noOfArticles; i++)
{
next = inventory[i].id;
j = i - 1;
while (j >= 0 && next < inventory[j].id)
{
inventory[j + 1].id = inventory[j].id;
j = j - 1;
}
inventory[j + 1].id = next;
}
}
void bubbleSortInventory(article inventory[], int noOfArticles)
{
int c, d, t;
for (c = 0; c < (noOfArticles - 1); c++)
{
for (d = 0; d < noOfArticles - c - 1; d++)
{
if (inventory[d].id > inventory[d + 1].id)
{
t = inventory[d].id;
inventory[d].id = inventory[d + 1].id;
inventory[d + 1].id = t;
}
}
}
}
void mergeSortInventory(article inventory[], int noOfArticles)
{
int temp[noOfArticles / 2];
int nLeft, nRight;
int i, iLeft, iRight;
if (noOfArticles > 1)
{
nLeft = noOfArticles / 2;
nRight = (int) ceil((double) noOfArticles / 2);
mergeSortInventory(inventory, nLeft);
mergeSortInventory(&inventory[noOfArticles / 2], nRight);
for (i = 0; i < nLeft; i++)
{
temp[i] = inventory[i].id;
}
i = 0;
iLeft = 0;
iRight = 0;
while (iLeft < nLeft && iRight < nRight)
{
if (temp[iLeft] < inventory[noOfArticles / 2 + iRight].id)
{
inventory[i].id = temp[iLeft];
iLeft = iLeft + 1;
}
else
{
inventory[i].id = inventory[noOfArticles / 2 + iRight].id;
iRight = iRight + 1;
}
i = i + 1;
}
while (iLeft < nLeft)
{
inventory[i].id = temp[iLeft];
i = i + 1;
iLeft = iLeft + 1;
}
}
}
If I'm correct in what you're asking, you want to keep the idCount array relational to the inventory array. I assume, since you're using article as a type that you've either typedef'd a variable to be an article, which would be pointless, or more likely you've built a struct of type article, then made an array of those structs, and called the array inventory.
If this is the case, then the most likely method of keeping them relational is to just include the count in the article struct.
There are methods of making the arrays relational without doing that, but they're pointless, because a simple four-line struct would do the trick, even if that struct was a wrapper around a different struct, or a header for another struct.
When sorting your records, you only assign the id member of your struct:
inventory[foo].id = inventory[bar].id;
You should assign the complete struct:
inventory[foo] = inventory[bar];
Just remember that temporaries must be of type article an not int so they allso can be assigne a complete struct and not only an id value

Resources