I am trying to set a value to array pointers and also set the pointers to NULL but when I try to run the program I am getting Segmentation fault (core dumped) and I believe it is because of what I have in the for loop. Please help
struct node {
int value;
node *next;
};
int main(){
node **adj;
int vert;
cout<<"Please enter the number of vertices: ";
cin>>vert;
adj = new node* [vert-1];
for (int x = 0; x <= vert-1; x++)//set all the names of the value.
{
adj[x]->value = x;
cout<< adj[x]->value;
adj[x] = NULL
}
return 0;
}
Using adj = new node* [vert-1]; just reserve memory for vert-1 pointers but, but you are assigning values to each of these pointers without reserving memory for them.
The correct way of doing what you want is:
node * adj;
..
adj = new node[vert-1]; // reserv memory for all information
// EDITED for out of array bounds: thanks #Leiaz
for (int x = 0; x < vert-1; x++)//set all the names of the value.
{
// now, you can modify a reserved memory portion
adj[x].value = x;
adj[x].next = NULL;
}
Related
I have a sparse matrix that the user has input and a linked list which stores only non-zero elements and ignore the all zeros. Now, My aim is from this linked list, try to get all the elements from the sparse matrix including the zeros and non-zeros element and display it.Someone show me a way of light please or some instructions or ideas
Sparse Matrix where user inputs all elements(Zeros & Non-Zeros )
int row;
int column;
int count=0;
int sparseMatrix[10][10];
cout<<"Enter Number of Rows: ";
cin>>row;
cout<<endl;
cout<<"Enter Number of Column: ";
cin>>column;
cout<<endl;
int i,j;
cout<<"Enter Elements in the Matrix: ";
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
cin>> sparseMatrix[i][j];
if (sparseMatrix[i][j]==0)
count++;
}
}
Link List which reads only Non-zero elements from the Sparse matrix and display them
void PrintList(struct node* start)
{
struct node *temp, *r, *s;
temp = r = s = start;
cout<<"row_position:";
while(temp != NULL)
{
cout<<temp->rowposition;
temp = temp->next;
}
cout<<endl;
printf("column_postion: ");
while(r != NULL)
{
cout<<r->columnposition;
r = r->next;
}
cout<<endl;
printf("Value: ");
while(s != NULL)
{
cout<<s->value;
s = s->next;
}
cout<<endl;
}
Creation of the link list nodes
struct node {
int value;
int rowposition;
int columnposition;
struct node *next;
};
void createNewNode (struct node** start, int NonZeroElement, int rowIndex, int columnIndex) // functions with parameter
{
struct node *temp, *r;
temp = *start;
if (temp==NULL)
{
temp=(struct node *) malloc (sizeof (struct node)); // creates a new node dynamically
temp -> value= NonZeroElement;
temp -> rowposition = rowIndex;
temp -> columnposition = columnIndex;
temp -> next=NULL;
*start = temp;
}
else
{
while (temp->next != NULL)
temp = temp->next;
// Create new node dynamically
r = (struct node *) malloc (sizeof(struct node));
r->value = NonZeroElement;
r->rowposition = rowIndex;
r->columnposition = columnIndex;
r->next = NULL;
temp->next = r;
}
}
My aim is to Display This Matrix as shown in this figure :
This is how the Matrix Should be displayed.My Aim
this is My output so far in the picture:
My Current Output of this code so far picture
I think that you need to consider the structure of your function call PrintList or your sparse Matrix data structure itself. Somewhere, either in the data structure or in the printList method should be the desired row by column structure of the sparse matrix. Consider the problem of having a 4x4 matrix with all zeroes except one value at [1,2]. The print method would not know that you want a 4x4 matrix at all with the exception of a single value at [1,2] unless either the print method received an input for number of rows and colums, or the data structure itself retained those values. This should allow for the function call to be more self-supportive and not relying on code in your main body to dictate that for you.
On another note, since you are going to have to print row x column values anyways there is little overhead in creating a nested for loop for rows and columns and checking whether or not the current linked list node row and column values are indeed the ones in the control variables for the nested loop structure. If not, you could print zero and when you get to the end of the inner for loop, you could print a new line to handle your code.
Of course, you could just have a linked list of values and you could use that to set the dimensionality of your matrix. In the example I gave, you would end up with 2 x 3 matrix printed out instead of maybe a desired 4 x 4 since the maximum row and column value were [1,2]. This would probably lead to undesired results, however, as matrix operations typically require very specific dimensionalities and that loss of information could give you bad results. Hope this helps!
This is my function to find the union of 2 set arrays located by a void pointer which I have issues running the first part to copy Set A into the union Set before doing comparisons with Set B
Right now the output of this code produces example
Set A = {1,5,7,8}
Union Set = {8,8,8,8} Copies last element of Set A 4 times
as the last loop causes the temp pointer to point at 8.
Do I have to create a new int pointer for each loop or is there a better way of going around this
// Note I cannot use vectors or sorting methods as it isnt in my learning scope yet so i'll have to stick to the primitive comparison way
//Definitions
// VoidPtr is Void*
// aSet is (VoidPtr *a = new VoidPtr[MAX])
// getElementI(aSet[i]) Returns an integer value at that position of the pointer
void findUnion(VoidPtr * aSet,VoidPtr * bSet,VoidPtr * unionSet,int sizea,int sizeb,int &sizec)
{
int* temp;
VoidPtr vp;
int notEqual = 0;
// Copy set a into set c
for(int i =0; i < sizea; i++)
{
*temp = getElementI(aSet[i]);
vp = temp;
unionSet[i] = vp;
}
}
int* temp;
Here temp is an uninitiaised pointer
*temp = getElementI(aSet[i]);
Here temp is being dereferenced. Dereferencing uninitialised pointers results in a program crash (at best) and all sorts of weird behaviour (at worst).
I'm finding it quite hard to understand what you really need to do, but allocating a new int pointer every time round the loop sounds reasonable. Like this
for(int i =0; i < sizea; i++)
{
int *temp = new int (getElementI(aSet[i]));
unionSet[i] = temp;
}
But I am guessing.
I am working on a program on C++ that's dealing with graphs.
I store graph as an adjacency list of nodes, and I have the corresponding structures declared in .h file as follows:
typedef struct Node {
int val;
struct Node * next;
} node;
typedef struct Graph {
int v;
node ** arr;
node ** arr2; // reserved list for a reversed directed graph.
} graph;
I have a function for initializing a graph defined as follows:
graph * creategraph(int v) { // v == number of vertices
int i;
graph * temp = (graph*)malloc(sizeof(graph));
temp->v = v;
for(i = 0; i < v; i++) {
temp->arr = (node**)malloc(v*sizeof(node*));
}
for(i = 0; i < v; i++) {
temp->arr[i] = NULL;
}
return temp;
}
I call the function as shown below to create a graph with number of vertices being equal to num_vertices:
graph * g = creategraph (num_vertices);
With num_vertices being equal to 200000, the "Access Violation Writing Location" exception is raised in graph * createGraph on the first execution of temp->arr[i] = NULL;.
Could anyone tell me what's the problem here? Thank you.
Here is a big problem:
for(i = 0; i < v; i++) {
temp->arr = (node**)malloc(v*sizeof(node*));
}
This allocates space for v nodes, but you only have a pointer to the last one you allocated. This is a memory leak. What you need to do is this:
temp->arr = (node**)malloc(v*sizeof(*temp->arr));
for(i = 0; i < v; i++) {
temp->arr[v] = (node*)malloc(sizeof(*temp->arr[0]));
}
Explanation:
arr is pointer to pointer to Node. First we need to allocate memory for v pointers. Then we need to allocate memory for a Node for each of these pointers.
Also note that it is unnecessary (and therefore bad) to cast malloc in C. If you're coding C++ it is necessary, so if you code "C" but are using a C++ compiler, you will need to cast the result.
Sidenote:
It's good practice to write int arr = malloc(n*sizeof(*arr)) or int arr = malloc(n*sizeof(arr[0])) instead of int arr = malloc(n*sizeof(int)). The reason is that if you in the future decides that you want to use long instead of int you will not have to change it on more than one place.
The problem is that you're needlessly allocating temp->arr v times, and leaking all of the previous allocations, so you use v times as much memory as you need to. You only need to allocate it once, so get rid of the loop.
Don't cast the return value of malloc(), while you're at it.
I'm quite sure this a simple issue, but I am trying to create a data structure that implements a dynamic array of structs.
Each struct will implement a linked list.
So I think that I want an array of pointers, which will point to the head of each list. For some reason, assigning method variables gives me a seg fault. I would love a little explanation of what I am doing wrong if you could. THANKS!
Oh, also, all of this is inside a class called Cache, so that is why there are some variables that don't appear to be defined, but I assure you they are. The program seg faults on indexes[i]->next = NULL; and the similar lines below that one.
typedef struct setNode {
char valid, dirty;
unsigned int tag;
setNode *next;
Cache *nextCache;
} set;
set **indexes;
arrayLength = cache_size / block_size;
indexes = new setNode *[arrayLength];
set *temp;
//Step through the array. The array is full of pointers to "Dummy Nodes"
for (size_t i = 0; i < arrayLength; i++) {
indexes[i]->next = NULL;
indexes[i]->valid = 0;
indexes[i]->dirty = 0;
indexes[i]->tag = 0;
//create empty linked list for each tag spot (One for direct mapped. etc...)
for(size_t i = 0; i < associativity; i++)
{
temp = indexes[i];
temp->next = new setNode;
temp = temp->next;
temp->next = NULL;
temp->valid = 0;
temp->dirty = 0;
temp->tag = 0;
}
}
}
indexes is an array of pointers to set objects, but they are uninitialized. They don't point to actual set objects, but merely to random memory locations. Trying to write to random memory is the very essence of the segmentation violation.
Before using your pointers, you need to allocate set objects and make the pointers point to them -- i.e.,
for (size_t i = 0; i < arrayLength; i++) {
indexes[i] = new set;
indexes[i]->next = NULL;
indexes[i]->valid = 0;
...
I am learning about pointers and the new operator in class.
In my readArray function I am to read in a size. Use the size to dynamically create an integer array. Then assign the array to a pointer, fill it, and return the size and array.
I believe I've gotten that part corrected and fixed but when I try to sort the array, i get the error "uninitialized local variable temp used."
The problem is though I get that error when I am trying to intialize it.
Any help appreciated thank you. Seeing my errors is very helpful for me.
#include <iostream>
using namespace std;
int* readArray(int&);
void sortArray(int *, const int * );
int main ()
{
int size = 0;
int *arrPTR = readArray(size);
const int *sizePTR = &size;
sortArray(arrPTR, sizePTR);
cout<<arrPTR[1]<<arrPTR[2]<<arrPTR[3]<<arrPTR[4];
system("pause");
return 0;
}
int* readArray(int &size)
{
cout<<"Enter a number for size of array.\n";
cin>>size;
int *arrPTR = new int[size];
for(int count = 0; count < (size-1); count++)
{
cout<<"Enter positive numbers to completely fill the array.\n";
cin>>*(arrPTR+count);
}
return arrPTR;
}
void sortArray(int *arrPTR, const int *sizePTR)
{
int *temp;
bool *swap;
do
{
swap = false;
for(int count = 0; count < (*sizePTR - 1); count++)
{
if(arrPTR[count] > arrPTR[count+1])
{
*temp = arrPTR[count];
arrPTR[count] = arrPTR[count+1];
arrPTR[count+1] = *temp;
*swap = true;
}
}
}while (swap);
}
You make temp an int pointer (uninitiialized), and then set the thing it points at (anything/nothing) to arrPTR[ccount]. Since you are using temp only to swap, it should be the same type as those being swapped, in this case: an int.
If it absolutely must be a pointer (there is no good reason for this, it's slow, confusing, adds potential for errors, and adds potential for memory leaks):
int *temp = new int; //make an int for the pointer to point at
bool *swap = new bool; //make an bool for the pointer to point at
do
{
//your code
}while (swap);
delete temp;
delete swap;
You declared temp as a pointer. You need to allocate it on the heap before dereferencing and assigning to it later. However perhaps a variable on the stack would be preferable?
FYI: You should be aware of the memory leak in readArray as well which is leaving callers responsible for calling delete []
Edit: I hope this will help clear up some of the other problems.
#include <iostream>
int* readArray(int&);
void sortArray(int*, int);
int main ()
{
int size(0); // use stack when possible
int *arrPTR = readArray(size);
sortArray(arrPTR, size);
// arrays are zero based index so loop from 0 to size
for (int index(0); index < size; ++index)
std::cout << arrPTR[index];
delete [] arrPTR; // remember to delete array or we have a memory leak!
// note: because we did new[] for an array we match it with delete[]
// if we just did new we would match it with delete
system("pause");
return 0;
}
int* readArray(int& size)
{
std::cout << "Enter a number for size of array.\n";
std::cin >> size;
int *arrPTR = new int[size]; // all news must be deleted!
// prefer pre-increment to post-increment where you can
for(int count(0); count < size; ++count)
{
std::cout << "Enter positive numbers to completely fill the array.\n";
std::cin >> arrPTR[count];
}
return arrPTR;
}
// passing size by value is fine (it may be smaller than pointer on some architectures)
void sortArray(int *arrPTR, int size)
{
// you may want to check if size >= 2 for sanity
// we do the two loops to avoid going out of bounds of array on last iteration
for(int i(0); i < size-1; ++i) // the first to compare (all except last)
{
for(int j(i+1); j < size; ++j) // the second to compare (all except first)
{
// do comparison
if (arrPTR[i] > arrPTR[j]) // from smallest to biggest (use < to go from biggest to smallest)
{
// swap if needed
int temp(arrPTR[i]); // put this on stack
arrPTR[i] = arrPTR[j];
arrPTR[j] = temp;
}
}
}
}
temp is a "pointer to int, which you're not initializing. When you say *temp = ... you're actually assigning to whatever temp happens to be pointing, but since you haven't told it what to point to, it can write pretty much anywhere in the address space of your program.
Because of the way you're using them, it seems that temp and swap shouldn't be pointers at all, just a plain int and bool.
You didn't initialize the temp pointer do when you dereference it you are writing to a random part of memory. Temp doesn't need to be a pointer, it can just be an int. Just replace EVERY instance of *temp with temp.