user3716193 user3716193 - 4 months ago 17
C Question

Conditional Statement for Array: Need to Store Values Not Equal to Value at Index in C

I have an integer pointer array b_members that contains something like the following values:

1 2 4

I want to find the values of b_members that are not equal to a specific value inside a loop and store them in another integer pointer array i_p.

For example, inside my loop at index 0 I want to find and store the two values in b_members not equal to 1, (i.e. 2 and 4). So for the first iteration

ip = 2 4

In the second iteration I want to store 1 and 4 in ip so

ip = 1 4

And in the third iteration I want to store 1 and 2 in ip so

ip = 1 2

I can do this in Matlab using the code below but I want to be able to do this in C.

b_members = [1 2 4];
for i = b_members
ip = b_members(b_members ~=i);

Heres what I have in C so far:

int *b_members;
int *i_p;

b_members = Get_b_members(B,j); // fills b_members with array like [1 2 4]

for(int i=0;i<B->Columns;++i){ // going through all of b_members
printf("%d ",b_members[i]);
// Finding b_members not equal to b_members[i]
for(int i2=0;i2<B->Columns;++i2){
if (b_members[i2] != b_members[i])
i_p = &b_members[i2];
} // End b_members for loop

I can't seem to get it to work the right way, i_p just keeps getting longer as the loop progresses and I only want it to contain the two integers at a time. Is there a way to do this like the Matlab code I provided above? Any help would be appreciated.


Using Saurav Sahu's suggestion this worked:

int **i_p = (int **)malloc(B->Columns * sizeof(int*));
int tmp;
for(int i=0;i<B->Columns;i++)
// Need to find b_members excluding b_members(i)
i_p[i] = (int *)malloc((B->Columns-1) * sizeof(int));
int idx = 0;
for(int jj=0;jj<=B->Columns;jj++)
if(i==jj) continue;
if(b_members[i] != b_members[jj])
i_p[i][idx++] = b_members[jj];
tmp = i;

for(int ii=0;ii<=tmp;++ii)
printf("\ti_p[%d] = ",ii);
for(int it=0;it<(B->Columns)-1;++it)
printf("%d ",i_p[ii][it]);


You can create pointer of integer pointers like this. Assign enough size to each integer pointers to store array_size-1 integers.

int a[] = {1, 2, 4};
int aSize = sizeof(a)/sizeof(a[0]);
int **b = (int **)malloc(aSize * sizeof(int*));;
for(int i = 0; i < aSize; i++){
     b[i] = (int *)malloc((aSize-1) * sizeof(int));
     int idx = 0;
     for(int j = 0; j < aSize; j++){
        if(i == j) continue;
        if(a[i] != a[j]) {
            b[i][idx++] = a[j];

It works perfectly.