简体   繁体   中英

How to access an array in all functions in my C program?

I am trying to create a segment tree for a competitive coding problem and this tree is represented using an array. I have functions namely, rangeMinQuery and updateTree which perform intermediate jobs on the array. I am unable to figure out how to manipulate the said array using the functions.

#include <stdio.h>
#include <stdlib.h>
#define bool int    
#define MAX(a,b) (((a)>(b))?(a):(b))

int upper_power_of_two(int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;

}

int getMid(int s, int e)
{
  return s + (e -s)/2;  
}

void updateValueUtil(int segTree[], int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of 
// this segment
if (i < ss || i > se)
    return;

// If the input index is in range of this node, then update 
// the value of the node and its children
st[si] = st[si] + diff;
if (se != ss)
{
    int mid = getMid(ss, se);
    updateValueUtil(st, ss, mid, i, diff, 2*si + 1);
    updateValueUtil(st, mid+1, se, i, diff, 2*si + 2);
}
}

void updateValue(int arr[], int segTree[], int n, int i, int new_val)
{
// Get the difference between new value and old value
int diff = new_val - arr[i];

// Update the value in array
arr[i] = new_val;

// Update the values of nodes in segment tree
updateValueUtil(st, 0, n-1, i, diff, 0);
}

int rangeMinquery(int segTree[],int qlow,int qhigh,int low,int high,int pos)
{
if(qlow<=low && qhigh >=high)
    return segTree[pos];

if(qlow>high || qhigh <low)
        return 9999999999;
int mid=(low+high)/2;
return MAX(rangeMinquery(segTree,qlow,qhigh,low,mid,2*pos+1),rangeMinquery(segTree,qlow,qhigh,mid+1,high,2*pos+2));
}

int main()
{
int n,q,x,l,r,i;
scanf("%d %d %d %d",&n,&q,&l,&r);
int a[n];
int segTree[upper_power_of_two(n)];
printf("%d\n",upper_power_of_two(n));
while(q--)
{
    int cmd,pos1,pos2;
    scanf("%d %d %d",&cmd,&pos1,&pos2);
    if(cmd==1)
    {
        a[pos1]+=pos2;
        updateValue(a,segTree,n,1,0);
    }
    if(cmd==2)
    {
        x=rangeMinquery(segTree,pos1,pos2,0,n,0);
        printf("%d\n",x);
    }
}
return 0;
}    

As you can see, I am trying to manipulate the array segTree and retain the values there itself. I would also like to know if there's a method to achieve the same on JAVA perhaps?

You can make global pointer...

//in global scope
int *segTree;

... and create array using malloc() operator:

//in main()
segTree = malloc(upper_power_of_two(n) * sizeof(int));

And now your array is global. But remember to free(segTree) before you end your program.

Btw. You should never create local arrays (on stack) with variable size like you did in given code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM