473,834 Members | 1,682 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Quandry with the following C code (Intermediate)

Hi all,

I have a slight problem understanding the following code that I saw on
a Unix-PAM tutorial (not OT!)

The following code will compare and old string to a new one, bombing
out if 'max' similar chars is exceeded.
------8<------

static
int compare(unsigne d char *old, unsigned char *new, int max)
{
unsigned char in_old[256];
int equal = 0;

(void)memset(in _old, 0, sizeof (in_old));

while (*old)
in_old[*(old++)]++;

while (*new) {
if (in_old[*new])
equal++;
new++;
}

if (equal > max)
return (1);

return (0);
}
------->8---------

I fail to see how the 2 strings are compared for character equality,
especially in how the

in_old[*(old++)]++;

line is used.
Could anyone please shed some light on this for me?

cheers

Bry

Nov 14 '05 #1
7 1294
Hi Bry,

In article <11************ **********@c13g 2000cwb.googleg roups.com>,
BMarsh wrote:
I have a slight problem understanding the following code that I saw on
a Unix-PAM tutorial (not OT!)

The following code will compare and old string to a new one, bombing
out if 'max' similar chars is exceeded.

------8<------

static
int compare(unsigne d char *old, unsigned char *new, int max)
{
unsigned char in_old[256];
int equal = 0;

(void)memset(in _old, 0, sizeof (in_old));

while (*old)
in_old[*(old++)]++;

while (*new) {
if (in_old[*new])
equal++;
new++;
}

if (equal > max)
return (1);

return (0);
}
------->8---------

I fail to see how the 2 strings are compared for character equality,
especially in how the

in_old[*(old++)]++;


The numerical character value of each character in the first input
string is used as an index for an array that counts the occurrences of
that character. Think about it like this: when the input string is "aab"
the first while loop does: in_old['a']++, in_old['a']++, in_old['b']++.

The second while loop checks for each character in the second input
string if it occurred in the first input string.

The first while loop could also be written as:

while (*old) {
in_old[*old]++;
old++;
}

Regards,
--
Rob van der Leek | rob(at)ricardis (dot)tudelft(do t)nl
Nov 14 '05 #2
Hi Rob,

Many thanks for your answer; it's cleared it up for me! I was totally
thrown off by the way the loop was written.

Thanks again,

Bryan.

Nov 14 '05 #3
"BMarsh" <b.*****@gmx.ne t> wrote:
The following code will compare and old string to a new one, bombing
out if 'max' similar chars is exceeded.
It doesn't do a compare the usual way. That is, it does something
completely different from strcmp().

(Oh, btw, if you insist on posting through Google-Broken-Beta, it would
be a good thing if you could get it not to strip all indentation. Your
code is hard to read this way.)
static
int compare(unsigne d char *old, unsigned char *new, int max)
{
unsigned char in_old[256];
First of all, you need to use UCHAR_MAX here, instead of 256. If you
don't, you may try to run this code on a Unicode system some day, and be
surprised when your function scribbles all over memory when you pass it
a string with Unicode characters over 256 in it.
int equal = 0;

(void)memset(in _old, 0, sizeof (in_old));
Lose the cast. It does no good, and clutters up the code.
while (*old)
in_old[*(old++)]++;
This tallies the number of occurrences of each separate character value
in the first string. There's a bug in it: what happens if you pass it a
string of UCHAR_MAX 'a's?
while (*new) {
if (in_old[*new])
equal++;
new++;
(See what I mean about the indentation?)

This checks each character in the second string, and if there were any
of the same character at all in the first string, counts it as "equal".
}

if (equal > max)
return (1);

return (0);
If the number of "equal" characters, that is, the number of chars in the
second string of which there was at least one in the first string,
exceeds the passed-in maximum, return 1, else 0. This could be more
easily written as

return (equal>max);
I fail to see how the 2 strings are compared for character equality,
So do I; they're not.

Note, in particular, the different treatment of "old" and "new".

For example, try to explain the discrepancy between

compare("abc", "dbbbe", 2)

and

compare("dbbbe" , "abc", 2)

Then, when you want an exercise I can't solve, try to explain _why_
someone would write a function like that, and then call it, sec,
"compare". The logic escapes me, I'm afraid. It's reasonably clear to me
_what_ this function does, but not why.
especially in how the

in_old[*(old++)]++;


The index entry corresponding to the character at the _current_ value of
old is increased (that is, the character now under the old pointer is
tallied); and old is moved to the next character. Not necessarily in
that order, or in any order at all, but since (old++) returns the old
value of old (so to speak) no matter which order is chosen, it doesn't
matter for the result.

Richard
Nov 14 '05 #4
Richard Bos wrote:

"BMarsh" <b.*****@gmx.ne t> wrote:

<snip>
static
int compare(unsigne d char *old, unsigned char *new, int max)
{
unsigned char in_old[256];


First of all, you need to use UCHAR_MAX here, instead of 256.


I think you mean "UCHAR_MAX + 1"
If you
don't, you may try to run this code on a Unicode system some day, and be
surprised when your function scribbles all over memory when you pass it
a string with Unicode characters over 256 in it.


I think you mean "over 255"

<snip>
Nov 14 '05 #5
infobahn <in******@btint ernet.com> wrote:
Richard Bos wrote:

"BMarsh" <b.*****@gmx.ne t> wrote:
unsigned char in_old[256];


First of all, you need to use UCHAR_MAX here, instead of 256.


I think you mean "UCHAR_MAX + 1"


Do we need "UCHAR_MAX + 1L" to cover the case of UCHAR_MAX
equal to UINT_MAX, say both 0xFFFF ?

Francois Grieu
Nov 14 '05 #6
Francois Grieu <fg****@francen et.fr> wrote:
infobahn <in******@btint ernet.com> wrote:
Richard Bos wrote:

"BMarsh" <b.*****@gmx.ne t> wrote:
> unsigned char in_old[256];

First of all, you need to use UCHAR_MAX here, instead of 256.
I think you mean "UCHAR_MAX + 1"


Yes (and yes).
Do we need "UCHAR_MAX + 1L" to cover the case of UCHAR_MAX
equal to UINT_MAX, say both 0xFFFF ?


In theory, yes. In practice, systems where SCHAR_MAX == INT_MAX or
UCHAR_MAX==UINT _MAX have so many problems that I wouldn't bother to
cater for them. Anyone porting code to that kind of implementation knows
he's getting into a hornets' (or mare's <g>) nest, and should take all
necessary precautions himself.
(And why stop there? What if UCHAR_MAX==ULON G_MAX? Could happen
(probably does happen) on a 32-bit embedded processor.)

Richard
Nov 14 '05 #7
Francois Grieu wrote:
infobahn <in******@btint ernet.com> wrote:
Richard Bos wrote:
First of all, you need to use UCHAR_MAX here, instead of 256.


I think you mean "UCHAR_MAX + 1"


Do we need "UCHAR_MAX + 1L" to cover the case of UCHAR_MAX
equal to UINT_MAX, say both 0xFFFF ?


Good spot, although I think we'd have to lump such an implementation
in with the DS9K. :-)

Actually, this really is a problem on CSILP32 systems such as
(some) DSPs, and the L suffix doesn't help on such systems.
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1901
by: Jack Carter | last post by:
I have been delegated to produce a tool that has python embedded in it. The desire is to have a command line interface that inherits all the python scripting functionality so people can use the tool either with a flat commandline entry like you would a debugger or with a script using scoping, loops and conditional. I am going from knowing nothing about python to almost nothing so the learning curve is rather
2
1847
by: The Plankmeister | last post by:
Hi, I am converting some queries from stored procedures in MS Access to MySQL, and have hit my first problem. The Access query references another stored procedure, which is where the problem lies. I have the following table data: (apologies if the columns aren't aligned properly... it looks ok in a fixed-width font) img_num img_page img_sect img_order
2
1416
by: Laphan | last post by:
Hi All Sorry for the spare info. It wasn't because I didn't want to display it. I just didn't know how to get the data that you needed. I think I've got it now so please note the following: 1) The DB is SQL 6.5. 2) My DDL for the tables in question:
3
1115
by: Fred | last post by:
Please consider the following two if() structures. The first one fails, yet the second works. Why? FWIW, I got the syntax of the first out of a working page. I figured moving it to another page would be harmless. What's going on here? The only major difference between the two pages that I can see so far is that in the new page (where the first if() structure fails), the control imgname is in a <form runat="server" method="post"> whereas in...
5
1242
by: swpulitzer | last post by:
I have a page that lists a bunch of objects, stored in a database, to the user. After each object I'd like to do something like: object1 object2 and so on, where "edit" and "delete" are links. Right now, each link uses GET to pass the object ID to the scripit that will deal with it. For example, the urls for the first object links are something like:
2
1742
by: Deano | last post by:
Hi, I have created a new form that reads in data from some intermediate tables. These intermediate tables are used to compile data for use in a report or the new form I have made. Having opened the new form with this intermediate data (it provides an aggregate view of various top-level codes in column A) the user can view and add projections.
0
853
by: TwistedPair | last post by:
All, I am monitoring a directory for file creation with the following code in VB Express: Dim watcher As New System.IO.FileSystemWatcher(WatchDirectory) Dim result result = watcher.WaitForChanged(System.IO.WatcherChangeTypes.Created)
4
3924
by: DavidB | last post by:
Im not sure if I am missing something obvious here or not so excuse me if this is a DFU question please... I have a report I am working on that includes the following data. Agency Name Vendor Name Contract Number Contract Description Agencies can have (and often do have) multiple contracts. I want my
15
2080
by: colemanj4 | last post by:
Here is what I have so far, it loops while the PW is incorrect, or until cancel is selected. I want it to lock the tables for adds, deletes, and edits when cancel is selected, and if the PW is correct. I want this to run when the DB is opened, I would also like the text box to be starred (*) out when text is input. Thanks for your help. ==============================
0
9796
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10544
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10214
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7755
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5624
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4425
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3079
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.