#include<stdio.h>
#include<conio.h>
//#include<alloc.h>
int* mergeSort(int*,int);
int* merge(int*,int*,int);
void main()
{
int n;int i=0;
int *a,*b;
scanf("%d",&n);
a=(int)malloc(n*sizeof(int));
for(;i<n;i++)
scanf("%d",&a[i]);
b=mergeSort(a,n);
for(i=0;i<n;i++)
printf("%d ",b[i]);
}
int* mergeSort(int *b,int n)
{
int temp,*s;
if(n>2)
{
mergeSort(b,n/2);
mergeSort(b+n/2,n-n/2);
s=merge(b,b+n/2,n);
return s;
}
else if(n==2)
{
if(b[0]>b[1])
{
temp=b[0];
b[0]=b[1];
b[1]=temp;
}
return;
}
}
int* merge(int* a,int* c,int n)
{
int i=0,j=0,k=0,
int* x;
while( (j ! =n/2) && (k != (n-n/2)) && (i < n))
{
if(a[j]<c[k])
{
x[i]=a[j];
j++;
i++;
}
else
{
x[i]=c[k];
k++;
i++;
}
}
for( ; j<n/2; j++,i++)
x[i]=a[j];
for( ; k < (n-n/2); k++,i++)
x[i]=c[k];
return x;
}
when i run this code,it hangs after inputting all the elements of the array in first for loop. Please help me, how can i correct it to make it work successfully? it hangs on calling the mergeSort function from main() function.
it hangs after inputting all the elements of the array in first for loop.
hangs? Are you sure... that's pretty good considering your merge code declares a pointer to an int:
int *x;
and never initializes it, then tries to jump to an offset (i) past it:
x[i]=a[j];
Change your code to this:
int *x = malloc(n * sizeof(int));
and it should stop crashing/hanging whatever.
FYI, whenever you malloc() you should free() right now you have memory leaks.
There are some things wrong, not only basic things like void main instead of int main but also eg the return; in mergeSort() which should return int* and the uninitialized x. Also one important thing about the algorithm: You seem to assume that n is a power of 2: you recursively divide by 2 and assume that it always is an untruncated integer.
For starters, the code doesn't compile in a C++ compiler (I know it's C code, but still...),
a couple of problems are:
line 11:
a=(int)malloc(n*sizeof(int));
why are you casting a pointer to an int? a is an int *
line 38:
return;
you are returning from mergeSort without a return value...that can't be good
I recommend that you fix all the compiler errors and warnings, then try again
Related
I have a function for the Collatz Conjecture that returns an int Array but I keep getting a segmentation fault error and am not sure why.
int n=1;
int* col fuction(int x){
int *totalList;
totalList[0]=x;
while (x != 1){
if (x%2==0){
x=x/2;
}else{
x= 3* x + 1;
}
totalList[n]= x;
n++;
}
totalList[n+1]=1;
return totalList;
}
It is suppose to return the integers in a row with commas in between each number. I call it as shown below:
int *colAns;
colAns= col(num);
for (int k =0; k< n; k++){
printf("%d", colAns[k]);
if(colAns[k] != 1){
printf(",");
}
}
printf("\n");
Your issue lies within the first few lines of col_function().
int* col_fuction(int x){
int *totalList;
totalList[0]=x;
// ...
}
When the int* called totalList gets created on the stack, it takes whatever value was previously there. There's a slim chance that the pointer value will be anything even owned by the process, let alone something valid/usable.
What you need is a dynamically-allocated value that can grow as values are added to it. For this, we use malloc to allocate a pre-determined amount of memory. Because the collatz function is recursive and the number of elements cannot be determined by merely looking at it, we cannot presume to know exactly how much memory it will take, so it should grow as numbers are added to it. For this, we use realloc. What's nice about realloc is that, if the first parameter is NULL, it is guaranteed by the standard to work like malloc.
The only other thing you really need is a couple of size_t values inside of a struct in order to keep track of the current index as well as the allocated space. Something like this should be sufficient:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE 100
typedef struct dynarray
{
int *values;
size_t allocated, used;
} dynarray;
int dynarray_init(dynarray *d)
{
memset(d, 0, sizeof(dynarray));
return 0;
}
int dynarray_deinit(dynarray *d)
{
free(d->values);
memset(d, 0, sizeof(dynarray));
return 0;
}
int dynarray_append(dynarray *d, int val)
{
int *tmp = NULL;
size_t i;
if(d->used + 1 >= d->allocated)
{
if((tmp = (int*)realloc(d->values, (d->allocated + CHUNK_SIZE)*sizeof(int))) == NULL)
{
perror("realloc() failure");
return 1;
}
else
{
d->values = tmp;
d->allocated += CHUNK_SIZE;
}
}
d->values[d->used++] = val;
}
Use dynarray_append() to add values to the list after it's been initialized.
Here i am writing a program which will do two things
1.get a number between 0 to 102,separate them and store them in an array
2.print the array for each number
For that purpose i wrote an if-else block which will initialize an array each time exactly according to the size of the current integer value which is denoted by variable called num
Meaning that if i have a number of single digit it will create an array of one element,If number is two digit long it will create an array of two element.But whenever i run the code i get the error mentioned in question title.
What might be the reason for that and how to solve this issue?
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int mirror(int num,int *arr,int i);
int main(){
int num=0,range=1;
while(num<102){
if(num<(int)pow(10,range))
{
int *arr =(int *)malloc(range*sizeof(int));
}else{
range+=1;
int *arr =(int *)malloc(range*sizeof(int));
}
int i = 0;
mirror(num,arr,i);
for(i=0;i<range;i++){
printf("%d ",arr[i]);
}
printf("\n");
num++;
}
}
int mirror(int num,int *arr,int i){
if(num == 0){
return 0;
}
arr[i] = num%10;
mirror(num/10,arr,++i);
}
The scope of pointer arr is only within the if-else block. So, it's not available outside of it.
Declare it outside the if-else block and you'll be able to use it as you have.
int *arr;
if(num<(int)pow(10,range))
{
arr = malloc(range*sizeof(int));
}else{
range += 1;
arr = malloc(range*sizeof(int));
}
Notice I have removed the cast of the malloc() return value. It's needless in C and error-prone. See: http://c-faq.com/malloc/mallocnocast.html
Array is local variable in if/else statement. You should put declaration of array in outer block of while and assignment in conditional block.
Given an array I am required to sort it in such a way that the first element is the smallest value, the second element is the largest, the third element is the second smallest element and so on.
But my code just prints the original array and I am not able to figure out why. Any advice would be appreciated.
#include <stdio.h>
void swap(int m, int n);
int main()
{
int i,j,A[10],n;
printf ("enter the number of array elements\n");
scanf ("%d", &n);
for (i=0;i<n;i++){
scanf ("%d", &A[i]);
}
for (i=0;i<n;i++){
if (i%2 == 0){
for (j=i;j<n;j++){
if (A[j] < A[i]){
swap(A[i],A[j]);
}
}
}
else if (i%2 != 0){
for (j=i;j<n;j++){
if (A[j] > A[i]){
swap (A[i],A[j]);
}
}
}
}
for(i=0;i<n;i++){
printf ("%d\n", A[i]);
}
return 0;
}
void swap( int m, int n)
{
int temp;
temp = m;
m = n;
n = temp;
}
You need to pass by reference using pointers.
void swap( int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
and change your code to call it like this
swap (&A[i],&A[j]);
For a solution that doesn't use pointers you can use a MACRO like this;
#define swap(x,y) do{int t=(x);(x)=(y);(y)=t;}while(0);
swap(A[i],A[j]);
Just define this at the top of your file and remove the swap function and prototype. It's all about scope, because the MACRO is just a text replace it's in the correct scope to use A[i].
The first problem I notice in your program is your swap function. In your swap function, your parameters are primitive data types. Thus, the function creates copies of integers "m" and "n", and switches the values within the scope of the function swap. But as soon as the function returns, you haven't really swapped anything. To actually swap the values in the array that you created in main, you need to do a pass by reference(pass in pointers to the variable you are trying to swap). Modify your swap function like this:
void swap( int *m, int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
Then inside your main, pass in the address of that value in the array using the & operator(address of). Here is an example: swap (&A[i],&A[j]);
Other suggestions:
Format your code so there is space between your conditions in your for loops.
Add comments.
#include<stdio.h>
int max = 100;
int main()
{
int a,j;
int * arr = (int*)malloc(sizeof(int)*max);
arr[max-1] = 1;
scanf("%d",&a);
factor( arr, a);
display(arr);
}
int factor( int arr[],int a)
{
if (!a) return;
int i,carry;
for(i=max-1;i>=0;i--)
{
arr[i] = (arr[i]*a) + carry;
carry = arr[i]/10;
arr[i] = arr[i]%10;
}
factor( arr, a-1);
}
int display(int arr[])
{
int i;
for ( i=0; i<max; i++)
{
printf("%d",arr[i]);
}
}
HI this is my program to find the factorial of numbers but its giving wrong answer i dont know why ...???
like when i give input as 13
then according to myprogram 13 is to be treated in array as 1 and 3 but its giving random numbers -1216731443 -121673144 . i think malloc is having problem , but i can't identify it .
thank you
I think the reason why you are getting "random" numbers is because you haven't initialized the carry variable. In the for loop, you are adding the un-initialized value of carry to the array which will cause undefined results.
Suppose I want to assign a value to a pointer.
int **a;
int** function(x){
int **b;
...
return b;
}
Is it possible?
a=function(x);
I am confused. Please let me know about it.
I have checked all the lines but only the pointer assignment seems to be wrong. So, here goes the problem codes (it might be complex to see but i am simplifying it by comments, please see the comments):
int* side_x_y(int ndx, int ndy,int flag_right_0_left_1_2,int flag_up_0_down_1_2){
int * node_number=(int*)malloc(sizeof(int)*(ndx*ndy*2+1));/// ***this pointer returns to segment_matrix function***///////
for(int i=1;i<=ndx*ndy*2;i++){
node_number[i]=0;
}
//int node_number[ndx+ndy]={};
//memset ( node_number, 0, (ndx+ndy)*sizeof (int) );
if(flag_up_0_down_1_2==0){
for(int i=1;i<=ndx;i++){
node_number[i]=i;
}
}
if(flag_up_0_down_1_2==1){
for(int i=1;i<=ndx;i++){
node_number[i]=(ndy-1)*ndx+1+i;
}
}
if(flag_right_0_left_1_2==0){
for(int i=1;i<=ndy;i++){
node_number[i]=ndx*i;
}
}
if(flag_right_0_left_1_2==0){
for(int i=1;i<=ndy;i++){
node_number[i]=1+ndx*(i-1);
}
}
return node_number;
}
int** segment_matrix(int ndx,int ndy){
int *nodes;
nodes=side_x_y(ndx, ndy,1,2);////*** here i have used nodes pointer***//// it returns only 1 where it should not be one///
//for(int i=0;i<ndy;i++)
//printf("%d",nodes[i]);
int ns=ndy-1;
int **segment=(int**)malloc(sizeof(int)*(ns+1));
for(int s=1;s<=ns;s++){
segment[s]=(int*)malloc(sizeof(int)*(2+1));
}
int kk=0;
for(int s=1;s<=ns;s++){
for(int i=1;i<=2;i++){
segment[s][i]=nodes[kk];
kk++;
if(i==2){
kk--;
}
}
}
return segment;
}
INSIDE THE main function:
int **nss;
nss=segment_matrix(ndx,ndy);////*** it is the most confusing part***/// please see
//printf("%d",nss[0][0]);
int Ns=ndy-1;
double bv_T_g=0;
double bv_T_q=0;
Complex *gamma=(Complex*)malloc(sizeof(Complex)*(Ns+1));
Complex *q=(Complex*)malloc(sizeof(Complex)*(Ns+1));
for(int i=1;i<=Ns;i++){
gamma[i]=assign_complex(bv_T_g,0);
q[i]=assign_complex(bv_T_q,0);
}
int** ns=(int**)malloc(sizeof(int*)*(Ns+1));
for(int i=1;i<=Ns;i++){
ns[i]=(int*)malloc(sizeof(int)*(2+1));
}
for(int i=1;i<=Ns;i++){
for(int j=1;j<=2;j++){
ns[i][j]=0;
}
}
As written, the code is unclear, but could be OK if the value assigned to b inside the function is safe. For example, if you allocated an array of integer pointers with calloc(), then the code would be fine:
int **function(size_t x)
{
int **b = calloc(x * sizeof(*b));
if (b == 0)
...report error...
return b;
}
...
a = function(23);
What would not be safe is returning a pointer to a local variable, such as:
int **function(size_t x)
{
int *array[23];
int **b = array;
return b; // Undefined behaviour
}
Yes, its possible. Why are you confused?
Yes.(short & simple answer to your question)
After your update :
1st mistake is
int **segment=(int**)malloc(sizeof(int)*(ns+1));
for(int s=1;s<=ns;s++){
segment[s]=(int*)malloc(sizeof(int)*(2+1));
i think there should be
int **segment=(int**)malloc(sizeof(int*)*(ns+1));
changes
sizeof(int)--> sizeof(int*)
2> in main()
nss=segment_matrix(ndx,ndy);
you are taking output of this function in nss which you havent use further??
3>
if(flag_right_0_left_1_2==0){
for(int i=1;i<=ndy;i++){
node_number[i]=1+ndx*(i-1);
}
you are suppose to write
if(flag_right_0_left_1_2==1){
for(int i=1;i<=ndy;i++){
node_number[i]=1+ndx*(i-1);
}