[C]Reverse array with only pointers - c

I tried to reverse an array using only pointers. The program runs without any errors but it doesn't reverse the array. What's wrong with my code?
#include <stdio.h>
#define SIZE 10
void arrayReverseOutput(int * arr);
void arrayInput(int * arr);
void printArray(int * arr);
int main(void)
{
int arr[SIZE] = { 0 };
arrayInput(arr);
arrayReverseOutput(arr);
printArray(arr);
system("PAUSE");
return 0;
}
void arrayInput(int * arr){
int i = 0;
for (i = 0; i < SIZE; i++){
scanf("%d",(arr+i));
}
}
void arrayReverseOutput(int * arr){
int i = 0;
int k = SIZE-1;
int temp = 0;
for (i = 0; i < SIZE; i++){
temp = *(arr+i);
*(arr+i) = *(arr + k);
*(arr + k) = temp;
k--;
}
}
void printArray(int * arr){
int i = 0;
for (i = 0; i < SIZE; i++){
printf("%d ", *(arr+i));
}
}

The problem is, you are actually reversing the array twice, negating any changes achieved by swapping places.
Loop over only half of the array while swapping the elements, like
for (i = 0; i < SIZE/2; i++)

You can use 2 pointers to do so
void arrayReverseOutput(int *head, int *tail)
{
int temp = 0;
do
{
temp = *tail;
*tail = *head;
*head = temp;
}
while (head++ < tail--);
}
Complete code
#include <stdio.h>
#define SIZE 10
void arrayReverseOutput(int *head, int *tail);
void arrayInput(int * arr);
void printArray(int * arr);
int main(void)
{
int arr[SIZE] = { 0 };
arrayInput(arr);
arrayReverseOutput(arr, &arr[SIZE - 1]);
printArray(arr);
return 0;
}
void arrayInput(int * arr)
{
int i = 0;
for (i = 0; i < SIZE; i++)
{
scanf("%d", (arr + i));
}
}
void arrayReverseOutput(int *head, int *tail)
{
int temp = 0;
do
{
temp = *tail;
*tail = *head;
*head = temp;
}
while (head++ < tail--);
}
void printArray(int * arr)
{
int i = 0;
for (i = 0; i < SIZE; i++)
{
printf("%d ", *(arr + i));
}
}

Related

How to create and return dynamic array with function parameters

I have a problem returning dynamic array pointer with function parameter. I get segfault
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n)
{
ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
*(ptr + (i - 1)) = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(array, n);
for(int i = 0; i < n; ++i)
{
printf("%d", array[i]);
}
return 0;
}
I have to fill my array with i*i, when I is from 1 to n.
I don't get any errors or warnings. Just message about segmentation fault. Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Memory must be allocate in the calling function, but not in called.
This variant works:
#include <stdio.h>
#include <stdlib.h>
void createArray(int *ptr, int n){
int i;
for(i = 1; i <= n; i++) {
*(ptr + (i - 1)) = i*i;
// fprintf(stdout,"%d %d\n", i, *(ptr + (i -1)));fflush(stdout);
}
}
int main() {
int i, n, *array = NULL;
void *pvc;
n = 5;
array = (int *)malloc(n * sizeof(int));
createArray(array, n);
for(i = 0; i < n; i++) {
fprintf(stdout,"%d %d\n", i, array[i]);fflush(stdout);
}
pvc = (void *)array;
free(pvc);
return 0;
}
You can change pointer through function parameters like this:
void createArray(int **ptr, int n)
{
*ptr = malloc(n * sizeof(int));
for(int i = 1; i <= n; ++i)
{
(*ptr)[i - 1] = i*i;
}
}
int main() {
int *array = NULL;
int n = 5;
createArray(&array, n);
Remember to call function like this: createArray(&array, n);

Issue with linked list and truth table

So I'm trying to print the truth table of a gate with n inputs using linked lists. I tried the following but I'm running into a problem. If I use the for loops with bincombs, to print all possible combinations and to calculate the result, on both report and myandlst as shown below, it crashes. The problem is easily fixed if I print everything in myandlst but I want to avoid it. Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
typedef struct data
{
int value;
struct data * next;
} Data;
typedef Data * DataList;
typedef int (*CallBack)(DataList *inlist, int n);
int report(CallBack f, int n);
int getbit(int x, int p);
void bincombs(int * x, int n);
int myandlst(DataList *list, int n);
int main( )
{
CallBack f ;
report(myandlst, 4);
return 0;
}
int getbit(int x, int p)
{
return (x & (1<<p))!=0;
}
void bincombs(int * x, int n)
{
static int state = 0 ;
int i;
for (i=0; i<n; i++)
{
*x = getbit (state, i);
x++;
}
state ++;
return;
}
Data * createData( int value)
{
Data * dataptr;
dataptr = malloc(sizeof (Data));
dataptr->value = value;
dataptr->next = NULL;
return dataptr;
}
void appendData(DataList *lstptr, Data *newptr)
{
if (*lstptr==NULL)
{
*lstptr = newptr;
return;
}
appendData( &((*lstptr)->next), newptr);
return;
}
int myandlst (DataList *inlist, int n)
{
int i,j,k;
int * x = malloc (n*sizeof(int));
k=1;
for (i=0; i< (1<<n) ; i++)
{
bincombs(x, n);
for (j=n-1; j>=0; j--)
{
k*=x[j];
}
appendData(inlist,createData(k));
k=1;
}
return 0;
}
int report(CallBack f, int n)
{
DataList temp ;
int * x = malloc (n*sizeof(int));
int i,j;
f(&temp, n);
for (i=0; i< (1<<n) ; i++)
{
bincombs(x, n);
for (j=n-1; j>=0; j--)
printf("%d ", x[j]);
printf("%d\n", temp -> value);
temp = temp->next;
}
printf("\n");
return 0;
}
P.S This is an assignment and therefore the structure of the program is standard. I can't avoid using linked lists or changing the format of the functions too much.

find all the elements of the matrix that are equal to the sum of the coordinates (i+j)

I can scan the matrix and determine the size but the output is blank.
Here is my code:
int createTripplesArrayAndList(int** mat, int row, int colum, Tripple **arr, Node** ls) {
int i, j, count=0, k = 0;
Node* head = *ls;
Node* tmp=NULL;
//count how many elements would be in the required array\list
for (i = 0; i < row; i++) {
for (j = 0; j < colum; j++) {
if (mat[i][j] == i + j) {
count++;
}
}
}
//going over the matrix and add the relevant elements to the array and to the list
(*arr) = (Tripple*)calloc(count, sizeof(Tripple));
for (i = 0; i < row; i++) {
for (j = 0; j < colum; j++) {
if (mat[i][j] == i + j) {
//add element to array
(*arr)[k].argument = mat[i][j];
(*arr)[k].i = i;
(*arr)[k].j = j;
//add element to the list
if (!head) {
tmp = (Node*)malloc(sizeof(Node));
tmp->value = (*arr)[k];
tmp->next = NULL;
head = tmp;
} else {
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->value = (*arr)[k];
new_node->next = NULL;
head->next = new_node;
head = new_node;
}
k++;
}
}
}
*ls = tmp;
return count;
}
void printTrripleArrAndList(Tripple* arr, int n, Node** ls) {
int i, j;
Node* curr = *ls;
printf("The tripple list is: ");
while (curr != NULL) {
printf("%d+%d=%d ->", curr->value.i, curr->value.j, curr->value.argument);
curr = curr->next;
}
printf("\nThe tripple array is: ");
for (i = 0; i < n; i++) {
printf("%d+%d = %d\n", arr[i].i,arr[i].j,arr[i].argument);
}
}
int ** createMat(int*n,int*m) {
int** mat = NULL;
int i, j, row, column;
//allocate and the matrix
printf("please enter size of row and colum: ");
scanf("%d%d", &row, &column);
mat = (int**)calloc(row, sizeof(int*));
for (i = 0; i < row; i++) {
mat[i] = (int*)calloc(column, sizeof(int));
}
//fill the matrix
printf("enter numbers for the matrix: ");
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
scanf("%d", &mat[i][j]);
}
}
*n = row;
*m = column;
return mat;
}
I used to get an error saying a value of type Node* cannot be assigned to an entity of type list* so I had to change them both to Node* The problematic area was:
head->next = new_node;
and:
curr = curr->next;
Please help.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define M 2
#define N 3
#define R 4
typedef struct Tripple {
int i;
int j;
int argument;
} Tripple;
typedef struct Node {
Tripple value;
struct Node* next;
} Node;
int* powerArray(int n);
void printPowArr(int* p, int n);
int** MatrixMultiplication(int firstMat[M][N], int secondMat[N][R]);
void printMatrix(int** p);
int createTripplesArrayAndList(int** mat, int row, int colum, Tripple **arr, Node** ls);
void printTrripleArrAndList(Tripple* arr, int n, Node** ls);
int** createMat(int* n, int*m);
This is my main :
void main() {
int *p;
int** newMat;
int p1[M][N] = { { 1, 4, 2 }, { 0, 3, 1 } };
int p2[N][R] = { { 1, 3, 1, 4 }, { 0, 2, 6, 4 }, { 4, 1, 0, 7 } };
int **mat=NULL;
int count;
int n = 0, m = 0, i = 0, j = 0;
p = powerArray(10);
printPowArr(p, 10);
newMat = MatrixMultiplication(p1, p2);
printMatrix(newMat);
Tripple* arr=NULL;
Node* ls=NULL;
mat=createMat(&n,&m);
count = createTripplesArrayAndList(mat, n, m, &arr, &ls);
printTrripleArrAndList(arr, count, &ls);
system("pause");
}
You are pointing both the head and head->next to new_node! This is absurd. Remove head->next = new_node.

Finding predecessor on a heap structure

This is the code i'm working and I have a function prototype to build :
node* pred ( int n,node * root) to find the predecessor
I have succeed with building the heap but here I am stuck.Please any held :D
#include<stdio.h>
#include<stdlib.h>
struct MaxHeap
{
int size;
int* array;
};
PrintArray(int* arr, int size);
struct MaxHeap* BuildMaxHeap(int* array, int size);
void HeapSort(int* array, int size);
void swap(int*a, int*b);
void MaxHeapify(struct MaxHeap* maxheap,int index);
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int size = (sizeof(arr))/(sizeof(arr[0]));
printf("\nGiven array of elements is :\n");
PrintArray(arr, size);
HeapSort(arr, size);
printf("\nThe sorted Array is :\n");
PrintArray(arr, size);
return 0;
}
PrintArray(int* arr, int size)
{
int i ;
for (i=0; i<size; i++)
printf("%5d", arr[i]);
printf("\n");
}
void swap(int*a, int*b)
{
int t = *a;
*a = *b;
*b = t;
}
void MaxHeapify(struct MaxHeap* maxheap,int index)
{
int largest = index;
int left = (index <<1) + 1;
int right = (index+1) << 1;
if(left < maxheap->size && maxheap->array[left] > maxheap->array[largest])
largest = left;
if(right < maxheap->size && maxheap->array[right] > maxheap->array[largest])
largest = right;
if(largest != index)
{
swap(&maxheap->array[index], &maxheap->array[largest]);
MaxHeapify(maxheap, largest);
}
}
struct MaxHeap* BuildMaxHeap(int* array, int size)
{
int i;
struct MaxHeap* maxheap = (struct MaxHeap*)malloc(sizeof(struct MaxHeap));
maxheap->size = size;
maxheap->array = array;
for(i= (maxheap->size - 2)/2; i>=0; i--)
MaxHeapify(maxheap, i);
return maxheap;
}
void HeapSort(int* array, int size)
{
struct MaxHeap* maxheap = BuildMaxHeap(array, size);
while(maxheap->size >1)
{
swap(&maxheap->array[0], &maxheap->array[maxheap->size-1]);
maxheap->size -= 1;
MaxHeapify(maxheap, 0);
}
}

global variable problem

i declare a global variable and use and modify its value in the function. Then i want to get the modified value of this global variable, it has some problem. Can anyone help me?
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
struct link
{
int freq;
char value[MAX];
struct link* right;
struct link* left;
};
typedef struct link node;
void sort(node *[], int);
node* create(char[], int);
void sright(node *[], int);
void Assign_Code(node*, int [], int);
void Delete_Tree(node *);
int test[720][720];
main()
{
node* ptr, * head;
int i, n, total = 0, u, c[256];
char str[MAX];
node* a[256];
int freq;
printf( "Huffman Algorithm\n");
printf("\nEnter the no. of letter to be coded:");
/*input the no. of letters*/
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the letter & frequency:");
/*input the letter & frequency*/
scanf("%s %d", str, &freq);
a[i] = create(str, freq);
}
while (n > 1)
{
sort(a, n);
u = a[0]->freq + a[1]->freq;
strcpy(str,a[0]->value);
strcat(str,a[1]->value);
ptr = create(str, u);
ptr->right = a[1];
ptr->left = a[0];
a[0] = ptr;
sright(a, n);
n--;
}
Assign_Code(a[0], c, 0);
//getch();
printf("Code: ");
for (i = 1; i <= n; i++)
{
printf("%d", test[0][i]);
}
printf("\n");
Delete_Tree(a[0]);
}
node* create(char a[], int x)
{
node* ptr;
ptr = (node *) malloc(256*sizeof(node));
ptr->freq = x;
strcpy( ptr->value , a);
ptr->right = ptr->left = NULL;
return(ptr);
}
void sort(node* a[], int n)
{
int i, j;
node* temp;
for (i = 0; i < n - 1; i++)
for (j = i; j < n; j++)
if (a[i]->freq > a[j]->freq)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
void sright(node* a[], int n)
{
int i;
for (i = 1; i < n - 1; i++)
a[i] = a[i + 1];
}
void Assign_Code(node* tree, int c[], int n)
{
int i;
if ((tree->left == NULL) && (tree->right == NULL))
{
printf("%s code: ", tree->value);
test[0][0]=tree->value;
for (i = 0; i < n; i++)
{
test[0][i+1]=c[i];
printf("%d", c[i]);
}
printf("\n");
}
else
{
c[n] = 1;
n++;
Assign_Code(tree->left, c, n);
c[n - 1] = 0;
Assign_Code(tree->right, c, n);
}
}
void Delete_Tree(node * root)
{
if(root!=NULL)
{
Delete_Tree(root->left);
Delete_Tree(root->right);
free(root);
}
}
Let me highlight the problem:
while (n > 1)
{
...
n--;
}
...
for (i = 1; i <= n; i++)
{
printf("%d", test[0][i]);
}
By the time the second loop starts n is one, and the printf is executed only once, so that you print the value of test[0][1] and only that.
The value of test[0][1] is overwritten many times (as many as the number of leaf nodes in the tree) in Assign_Code:
void Assign_Code(node* tree, int c[], int n)
{
if ((tree->left == NULL) && (tree->right == NULL))
{
...
for (i = 0; i < n; i++)
{
test[0][i+1]=c[i];
}
}
...
}
Now, because of the way you are traversing the tree the last time test[0][1] is overwritten is for a Huffman code that has a '0' as first character.
As a side note:
node* create(char a[], int x)
{
node* ptr;
ptr = (node *) malloc(256*sizeof(node)); // <--- This is wrong
ptr->freq = x;
strcpy( ptr->value , a);
ptr->right = ptr->left = NULL;
return(ptr);
}
There is no reason to allocate 256 times the size of node to store one node. You are creating a node and storing it in an array of pointers to nodes. Allocate one node there, like this:
malloc (sizeof (node)); or malloc ((sizeof (*ptr));
you can store the n value to some temporary variables, after you get the
values.
Then use the temporary variable in your for loop condition.
scanf("%d", &n);
int temp = n ;
for (i = 1; i <= temp ; i++)
{
printf("%d", test[0][i]);
}

Resources