Logo

Programming-Idioms

History of Idiom 20 > diff from v45 to v46

Edit summary for version 46 by programming-idioms.org:
[C] Typo in comments

Version 45

2017-09-01, 18:32:24

Version 46

2017-12-28, 22:35:23

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Imports
#include <string.h>
Imports
#include <string.h>
Code
void search(void ***m,void *x,size_t memb_size,int len_x,int len_y,int *i,int *j)
{
	for(*i=0;*i<len_x;*i+=1)
	{
		for(*j=0;*j<len_y;*j+=1)
		{
			if(!memcmp(m[*i][*j],x,memb_size))
			{
				return;
			}
		}
	}
	*i=*j=-1;
}
Code
void search(void ***m,void *x,size_t memb_size,int len_x,int len_y,int *i,int *j)
{
	for(*i=0;*i<len_x;*i+=1)
	{
		for(*j=0;*j<len_y;*j+=1)
		{
			if(!memcmp(m[*i][*j],x,memb_size))
			{
				return;
			}
		}
	}
	*i=*j=-1;
}
Comments bubble
m is a matrix containing type (void *) pointing to the data (can be anyting)

x is the pointer to the data to look for

memb_size is the size of one element in bytes (to be able to compare anything)

len_x and len_y are the dimensions

i and j are passed by reference and contain the values, or -1 if x was not found, after the function returned.
Comments bubble
m is a matrix containing type (void *) pointing to the data (can be anything)

x is the pointer to the data to look for

memb_size is the size of one element in bytes (to be able to compare anything)

len_x and len_y are the dimensions

i and j are passed by reference and contain the values, or -1 if x was not found, after the function returned.