Sunday, February 28, 2010

comp.lang.c - 25 new messages in 10 topics - digest

comp.lang.c
http://groups.google.com/group/comp.lang.c?hl=en

comp.lang.c@googlegroups.com

Today's topics:

* usage of size_t - 4 messages, 4 authors
http://groups.google.com/group/comp.lang.c/t/19e0ad96d01b9898?hl=en
* What is the explanation? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/43491a16c11fd4e0?hl=en
* Error with threads opening files - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c/t/2dc4e1c41436509b?hl=en
* More quirks importing from bsd - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c/t/3879f22a8a1b80ee?hl=en
* substring finding problem! - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.c/t/cf9bd97208e0c3a3?hl=en
* initialize for a 2-D dynamic array. - 5 messages, 3 authors
http://groups.google.com/group/comp.lang.c/t/10b972fd49323b34?hl=en
* fputs and fprintf - 5 messages, 4 authors
http://groups.google.com/group/comp.lang.c/t/d665d0bf528f7433?hl=en
* Plan 9's c compiler - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/110a62f10b04cea0?hl=en
* automated sub-string search/replace algorithm... - 1 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/6c021e75cf801832?hl=en
* Efficency and the standard library - 2 messages, 1 author
http://groups.google.com/group/comp.lang.c/t/ad9fea19f2f7dd61?hl=en

==============================================================================
TOPIC: usage of size_t
http://groups.google.com/group/comp.lang.c/t/19e0ad96d01b9898?hl=en
==============================================================================

== 1 of 4 ==
Date: Sun, Feb 28 2010 5:08 am
From: Nick Keighley


On 27 Feb, 22:11, Seebs <usenet-nos...@seebs.net> wrote:
> On 2010-02-27, Julienne Walker <happyfro...@hotmail.com> wrote:
> > On Feb 27, 11:52 am, spinoza1111 <spinoza1...@yahoo.com> wrote:

Julienne Walker wrote:
***
By the time you plug the holes, you'll have something more like Java
or C#.
***

> >> Which some brilliant people at Sun and Microsoft have done. Moore's
> >> Law should take care of the rest. Why is C not given a hero's funeral?
>
> > For the same reason COBOL hasn't: there's a great deal of existing
> > code out in the wild.
>
> Not just that.  There are problems where Moore's Law isn't enough, because
> ANY improvement in speed is pretty worthwhile, and where native C tends
> to win.
>
> Kernels, for instance.

and garbage collectors


== 2 of 4 ==
Date: Sun, Feb 28 2010 5:36 am
From: Moi


On Sun, 28 Feb 2010 05:08:08 -0800, Nick Keighley wrote:

> On 27 Feb, 22:11, Seebs <usenet-nos...@seebs.net> wrote:
>> On 2010-02-27, Julienne Walker <happyfro...@hotmail.com> wrote:
>> > On Feb 27, 11:52 am, spinoza1111 <spinoza1...@yahoo.com> wrote:
>

>
>> >> Which some brilliant people at Sun and Microsoft have done. Moore's
>> >> Law should take care of the rest. Why is C not given a hero's
>> >> funeral?
>>
>> > For the same reason COBOL hasn't: there's a great deal of existing
>> > code out in the wild.
>>
>> Not just that.  There are problems where Moore's Law isn't enough,
>> because ANY improvement in speed is pretty worthwhile, and where native
>> C tends to win.
>>
>> Kernels, for instance.
>
> and garbage collectors

And algorithms and algorithm books.
In my observation, even Knuth writes demonstration programs in C, and Cweb.
C is a sort of portable (M)MIX.

HTH,
AvK


== 3 of 4 ==
Date: Sun, Feb 28 2010 6:56 am
From: spinoza1111


On Feb 28, 9:08 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
> On 27 Feb, 22:11, Seebs <usenet-nos...@seebs.net> wrote:
>
> > On 2010-02-27, Julienne Walker <happyfro...@hotmail.com> wrote:
> > > On Feb 27, 11:52 am,spinoza1111<spinoza1...@yahoo.com> wrote:
> Julienne Walker wrote:
>
> ***
> By the time you plug the holes, you'll have something more like Java
> or C#.
> ***
>
> > >> Which some brilliant people at Sun and Microsoft have done. Moore's
> > >> Law should take care of the rest. Why is C not given a hero's funeral?
>
> > > For the same reason COBOL hasn't: there's a great deal of existing
> > > code out in the wild.
>
> > Not just that.  There are problems where Moore's Law isn't enough, because
> > ANY improvement in speed is pretty worthwhile, and where native C tends
> > to win.
>
> > Kernels, for instance.
>
> and garbage collectors

But this doesn't justify using C for much more. And based on my
experience in IBM, I'd guess that the C code is generated or highly
structured so as to be "quirky".


== 4 of 4 ==
Date: Sun, Feb 28 2010 7:55 am
From: Julienne Walker


On Feb 28, 8:02 am, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
> On 26 Feb, 16:27, Julienne Walker <happyfro...@hotmail.com> wrote:
> > On Feb 26, 3:00 am, spinoza1111 <spinoza1...@yahoo.com> wrote:
> > > On Feb 26, 3:36 am, Julienne Walker <happyfro...@hotmail.com> wrote:
> > > > On Feb 25, 1:46 pm,spinoza1111<spinoza1...@yahoo.com> wrote:
> > > > > On Feb 25, 10:54 pm, Richard Heathfield <r...@see.sig.invalid> wrote:
> > > > > > spinoza1111wrote:
>
> > > > > I saw no try catch in your code.
>
> > > > Probably because there's no such construct in portable C. You can
> > > > simulate exceptions using standard C, but it gets ugly very quickly.
>
> > > Pity.
>
> > Not really. C isn't a language that lends itself to proper exception
> > support because there are too many points where exceptions fall flat.
>
> I'm surprised
>
> > One can see the problems by looking at C++. C++ exceptions are useful
> > to a point, but in my opinion they're not nearly as beneficial as they
> > would be if C++ integrated them more fully into the language (throwing
> > an exception on out of bounds array indexing, for example)
>
> that might be nice, though it would be a rather different language

Yes, that's the point. Not being able to use exceptions is only a pity
if C were in any way suitable for supporting exceptions. ;-)

> > and had native garbage collection.
>
> I don't see why garbage collection is necessary for exceptions to work
> properly. I always thought RAII was one of C++'s nicer features. With
> Java etal you are never really sure when the resource disappears.

The problem with RAII is in handling errors on destruction. In C++ you
*do not* throw from a destructor to avoid the risk of throwing from a
destructor while a previously thrown exception is unwinding the stack.
If this happens, the default behavior kills the process with a call to
abort().

Garbage collection removes a large number of cases where you might use
RAII (as memory is the most common resource). The problem still
exists, but it's greatly minimized. That's why I included garbage
collection. In more general terms, more management by the language
(runtime) is needed for exceptions to be properly integrated, and if
they're not properly integrated, you have a half-assed solution.

> > By the time you plug the holes, you'll have something more like Java
> > or C#.
>
> well only because you insisted on garbage collection...

Garbage collection is actually a minor feature in this case. It isn't
strictly necessary, but when methods of finalization are considered
one feels pressed to manage memory as well. Otherwise you'll end up
with, using two common examples, a ton of "smart objects" under an
RAII method or far more finally blocks than many programmers would be
comfortable with in a try/catch/finally method.

==============================================================================
TOPIC: What is the explanation?
http://groups.google.com/group/comp.lang.c/t/43491a16c11fd4e0?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Feb 28 2010 5:14 am
From: Kaz Kylheku


On 2010-02-28, Nick <3-nospam@temporary-address.org.uk> wrote:
> Spectrum Basic did that well before Perl IIRC. Useful for writing
> things like:
> PRINT a$ OR 'nothing'

Lisp!

(or a1 a2 a3 ... an)

The arguments ai are evaluated in order, stopping at the first one which
yields true (a value other than nil), in which case that value is the
result. Otherwise, the result is nil.

This feature is described in the Lisp 1.5 manual whose preface is dated
August 17, 1962. (Appendix A, Functions and Constants in the LISP
System).

==============================================================================
TOPIC: Error with threads opening files
http://groups.google.com/group/comp.lang.c/t/2dc4e1c41436509b?hl=en
==============================================================================

== 1 of 2 ==
Date: Sun, Feb 28 2010 5:16 am
From: Andre Ramaciotti


Richard Heathfield <rjh@see.sig.invalid> writes:

> lancer6238@yahoo.com wrote:
>> [...] each thread only opens (using a FILE *fin declared in
>> Process()) and works on a portion of the data files using a
>> start_index and an end_index. For example, if there are 100 files,
>> then each thread will handle filename[0] to filename[24], filename[25]
>> to filename[49], filename[50] to filename[74] and filename[75] to
>> filename[99] respectively. After they're done, there is a pthread_join
>> in main() for all 4 threads.
>>
>> I have checked that the filenames have been stored correctly, both in
>> main() and Process(). However, I keep getting segmentation fault here,
>> in Process():
>>
>> for (i = start_index, i <= end_index ; i++)
>> fin = fopen(filename[i], "rb"); <--- Seg fault
>
> Given the tiny amount of information available, my best guess can only be a
> guess:
>
> s/<=/<//

I'll make another guess: s/,/;/ after start_index.


== 2 of 2 ==
Date: Sun, Feb 28 2010 5:48 am
From: Ben Bacarisse


Andre Ramaciotti <andre.ramaciotti@gmail.com> writes:

> Richard Heathfield <rjh@see.sig.invalid> writes:
>
>> lancer6238@yahoo.com wrote:
<snip>
>>> for (i = start_index, i <= end_index ; i++)
>>> fin = fopen(filename[i], "rb"); <--- Seg fault
>>
>> Given the tiny amount of information available, my best guess can only be a
>> guess:
>>
>> s/<=/<//
>
> I'll make another guess: s/,/;/ after start_index.

Unlikely -- just because I don't recall ever seeing a compiler that
would accept the for loop as presented. It is more likely a typing
error. The other reason this seems likely is that the loop, as shown,
is pointless since it overwrites the same fin variable every time.
There is a lot of evidence that this is "something like" the code
being debugged.

To the OP: make sure you include program text using some automatic
method rather than typing it in. At the very least, I'd want to see
the code that sets up the filename data and the code that chooses the
start and end indexes. If it not the fencepost error that Richard
Heathfield has suggested, it is most likely something to do with the
filename data, but people here need to see the real code.

--
Ben.

==============================================================================
TOPIC: More quirks importing from bsd
http://groups.google.com/group/comp.lang.c/t/3879f22a8a1b80ee?hl=en
==============================================================================

== 1 of 2 ==
Date: Sun, Feb 28 2010 5:27 am
From: Moi


On Sun, 28 Feb 2010 13:08:02 +0000, Mark Hobley wrote:

> In comp.unix.programmer santosh <santosh.k83@gmail.com> wrote:
>> Since the source is available, and it's easy to implement your own as
>> well, with the same semantics, it's not a big portability problem,
>> AFAICS.
>
> Yeah. I am just deciding how to do that now. I have stumbled across a
> library called libnostd that contains an implementation of this. I could
> use that library. I am a bit concerned about the transparency issue of
> that though, because it still uses string.h and this means that code
> using string.h but using strlcat will work directly on some systems, but
> not on other systems where strlcat is not implement (so much for
> standard C libraries huh!).

The strlxxx() and strpxxx() families of functions are extensions to
the stdlibrary. If you can live with polluting the library, it is
easiest to just add them to libc. Otherwise, you'll have to put them
in a separate library, obviously.

(IMHO: the and str[lp]xxx() are a very useful extention; I never
use the return values (the first argument, which the caller already has)
from strcpy() and memcpy().

>
> I am thinking it might be better to create a new header bsdlib.h
> containing the additional functionality, and using that. However, this
> may then create another problem in that I need to provide fixups so that
> code including bsdlib.h and string.h on a host that includes strlcat in
> the string.h header does not create a conflicting definition. Also, what
> do I do about alternative implementations of strlcat, which zero the
> last byte of the buffer? Do I just drop support for those platforms, or
> do I create a new function name with equal functionality to avoid
> ambiguity? What a mess!

The clean way is to provide your own versions, and possibly
#define strlcpy mystrlcpy
, etc.

>
> The other thing is, I have some fixups to make to glibc anyway to make
> it portable across IA32 compatible machines (Currently it contains
> embedded invalid instructions which do not work on traditional Pentiums,
> the Cyrix 686, and the AMD K5 and AMD K6, and can cause a crash when the
> libraries are transferred between machines containing these processors.)

Well, this is what open source is all about. Why distribute binaries
if you can compile on (for) the target platform ?

Why would you distribute glibc anyway ? You expect target platforms without
a usable glibc ? Why not have the users install it themselves ?
(or let the package manager handle it)

HTH,
AvK


== 2 of 2 ==
Date: Sun, Feb 28 2010 8:08 am
From: markhobley@hotpop.donottypethisbit.com (Mark Hobley)


In comp.unix.programmer Moi <root@invalid.address.org> wrote:

> Well, this is what open source is all about. Why distribute binaries
> if you can compile on (for) the target platform ?

The core system will be installable from a cdrom, and the rest of the binary
files will be shared via the network. All machines are IA32 compatible, so as
long as I can build to this the binaries will be portable.

Mark.

> Why would you distribute glibc anyway ? You expect target platforms without
> a usable glibc ?

I was hoping that my source packages would be usable within other
distributions irrespective of which C library was being used. This enables me
to bootstrap. I need to have the code working on an existing system, before I
can deploy a revised system.

This would also mean that third parties can use my packages without having to
install my version of the C library.

Mark.

--
Mark Hobley
Linux User: #370818 http://markhobley.yi.org/


==============================================================================
TOPIC: substring finding problem!
http://groups.google.com/group/comp.lang.c/t/cf9bd97208e0c3a3?hl=en
==============================================================================

== 1 of 2 ==
Date: Sun, Feb 28 2010 5:34 am
From: Nick Keighley


On 28 Feb, 05:45, spinoza1111 <spinoza1...@yahoo.com> wrote:
> On Feb 28, 1:08 am, Nick Keighley <nick_keighley_nos...@hotmail.com>
> > On 26 Feb, 16:48,spinoza1111<spinoza1...@yahoo.com> wrote:
> > > On Feb 26, 5:15 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
> > > > On 25 Feb, 19:23,spinoza1111<spinoza1...@yahoo.com> wrote:
> > > > > On Feb 25, 5:29 pm, blm...@myrealbox.com <blm...@myrealbox.com> wrote:
> > > > > > In article <bdac8263-e941-4955-9875-44d4ff741...@k18g2000prf.googlegroups.com>,

<snip>

> > > Your own thought seems to proceed in true regular guy mode:
>
> > have I been insulted? Is it good or bad to be a "regular guy"?
>
> Bad. We need stand up guys here.

is a "stand up guy" different from a "regular guy"? I'm afraid I don't
speak american.

<snip>

> > > [...] the length may be inexpressible if it exceeds
> > > what in C is called "long long" precision. OO systems handle this
> > > cleanly: it gives C the willies.
>
> > OO isn't magic. If there is a way to do this then C will be able to do
> > it as well. Yeah, I know I'm drifting into "all useful programming
> > languages are turing complete and therefore in a sense equivalent".
[...]
> > But I'll argue that this particular problem doesn't require the C
> > programmer to implement an interpreter.
>
> "Interpreter" has become to mean "does extra stuff".

I considered using "translator", I wasn't insisting on a particular
implementation technology but on the concept that one language can be
used to implement another.

> But that's not
> what an interpreter is. One of the least celebrated discoveries in
> computer science was made by Bell Northern Research developers in the
> 1970s: threaded code and just in time, which solves the problem that
> interpretation has to interpret everything all the time.

<snip>

> > > > > [a nul terminated string] mandates Eurocentric left to right processing
>
> > > > nope. You are confusing representation and presentation. The nul isn't
> > > > at the right hand end it's at the largest address. If the display
> > > > device chooses to print r-to-l instead of l-to-r it makes not [the]
> > > > blindest bit of difference.
>
> > > What on EARTH does the word "print" mean?
>
> > to make marks on a piece of paper.
>
> You still do that? Your only output device is a printer? What, are you
> logged on to the Web using a Western Union teletypewriter? Wow.

fine. So get yourself a better web client.


> > > I'm aware that left to right can be reversed by layering software,
> > > something at which C programmers suck because C sucks at it.
>
> > > Your solution forces the wogs to get wog devices that print backwards.
>
> > or a device that isn't biased. Like a laser printer. They basically
> > don't care what direction they go in. I suspect it wouldn't take much
> > to make a dot-matrix or ink-jet do similar stuff. I can print pictures
> > on my dot-matrix and pictures aren't euro-centric. Those of us that
> > stayed in the industry are aware that the chain printer is no more.
> > (not that those were direction biased either!)
>
> You say that, but use the word "print".

so what did you mean by "mandates left to right processing"


> > > However, it still forces developers to think eurocentrically with the
> > > result that the non-Latin output is necessarily a second choice.
>
> > we're repeating ourselves. But I think my point about representation
> > and presentation (or display) is worth thinking about.
>
> No, it's not, because can is not will. I certainly know, living in
> China, that the invention of the bit mapped display and laser printer
> was great for Asia.

good

<snip>

== 2 of 2 ==
Date: Sun, Feb 28 2010 7:04 am
From: Julienne Walker


On Feb 28, 12:34 am, spinoza1111 <spinoza1...@yahoo.com> wrote:
> On Feb 28, 6:22 am, Julienne Walker <happyfro...@hotmail.com> wrote:
> > On Feb 27, 1:27 am,spinoza1111<spinoza1...@yahoo.com> wrote:
>
> > > I believe I express mostly disapproval about speed of coding as a way
> > > of dodging issues, not speed of coding per se. For example, I didn't
> > > like it at all when Brian Kernighan, in the recent O'Reilly collection
> > > Beautiful Code, praised Rob Pike for only taking an hour to write a
> > > "regular expression processor" because:
>
> > > * Pike's code wasn't a full or true regular expression processor
> > > * The fact that it took an hour doesn't change the above
>
> > At the risk of getting off on a tangent, I'm wondering if you read
> > that chapter carefully, or the book from which the example was taken.
> > The requirements for the "regular expression package" were, and I
> > quote:
>
> > "I suggested to Rob that we find the smallest regular expression
> > package that would illustrate the basic ideas while still recognizing
> > a useful and nontrivial class of patterns. Ideally, the code would fit
> > on a single page."
>
> I read that passage. However, I'd encountered "regular expressions" in
> 1971 when I read "Formal Languages and Their Relation to Automata" by
> Hopcroft and Ullman before I had access to a computer. I regard myself
> as privileged to start with math before wide availability of
> computers, since I had to figure more out.
>
> In this book, a "regular expression" was not a regular expression
> unless it was a complete fullfunction regular expression, because it
> was REQUIRED to be able to parse any regular string. What happened IMO
> was that Kernighan Pike et al. seized upon the concept, stole it from
> their Princeton/Bell Labs coworkers, and used it to designate a hack:
> the unix grep horror.
>
> <snip>
>
> The problem is that "regular expression" already has a meaning, and
> Rob's "regular expression package that would ... recognize [some]
> useful ... patterns" was NOT a regular expression recognizer. In a
> university class, where the assignment was "develop a regular
> expression package that parses and applies regular expressions", Rob
> would have received an F.

So my suspicion was partially correct. You're judging the code based
on a different specification than the one intended. Kernighan and Pike
clearly meant "grep-style" regular expressions rather than
"mathematical" regular expressions. Seeing as how the book was written
in 1998 and the term "regular expression" has solidified as meaning
the former, it's not unreasonable for them to neglect defining it.

To avoid being nonconstructive in my criticism, I'll offer you another
exercise in your relearning of C: write a full and true mathematical
regular expression parser that meets Kernighan's stated requirements
of being small enough for inclusion in that particular section
("Ideally, the code would fit on a single page."), and illustrates the
basic ideas of regular expressions as a simplifying notation in
problem solving. I won't ask that it be done in an hour or two,
because how long it takes is not an indicator of quality. ;-)

==============================================================================
TOPIC: initialize for a 2-D dynamic array.
http://groups.google.com/group/comp.lang.c/t/10b972fd49323b34?hl=en
==============================================================================

== 1 of 5 ==
Date: Sun, Feb 28 2010 6:02 am
From: Ben Bacarisse


ike@localhost.claranet.nl (Ike Naar) writes:

> In article <slrnhok9jn.mqh.usenet-nospam@guild.seebs.net>,
> Seebs <usenet-nospam@seebs.net> wrote:
>>On 2010-02-28, MBALOVER <mbalover9@gmail.com> wrote:
<snip>
>>> I did a search and found:
>>> 1. array = (** unsigned char) calloc(NROW, sizeof(unsigned char*));
>>
>>This is clearly incorrect.
>
> Why? It looks like mbalover is constructing a "dynamic 2D array"
> as an array of pointers, pointing to 1D arrays. What's incorrect
> about that?

It has a syntax error. (** unsigned char) is not a valid cast operator.

<snip>
--
Ben.


== 2 of 5 ==
Date: Sun, Feb 28 2010 6:28 am
From: Ben Bacarisse


MBALOVER <mbalover9@gmail.com> writes:

> I want to create a 2D dynamic array and then initialize all elements
> with 0.

This is a FAQ: http://c-faq.com/aryptr/dynmuldimary.html

I like the second suggested method, though I tend to write it like this:

if (ptrs = malloc(NROWS * sizeof *ptrs))
if (ptrs[0] = malloc(NCOLS * NROWS * sizeof *ptrs[0]))
for (int r = 1; r < NROWS; r++)
ptrs[r] = &ptrs[r - 1][NCOLS];
else free(ptrs);

where 'ptrs' is of type T ** for some type T. Using only two malloc
calls make checking and freeing simpler.

> I am wondering if I can replace calloc in line 1 by malloc function
> and still get a 2D array with all array[i][j]=0.

To get a zero-initialised array insert a memset call in the inner if:

if (ptrs[0] = malloc(NCOLS * NROWS * sizeof *ptrs[0])) {
memset(ptrs[0], 0, NCOLS * NROWS * sizeof *ptrs[0]);
for (int r = 1; r < NROWS; r++)
ptrs[r] = &ptrs[r - 1][NCOLS];
}
else free(ptrs);

but this is only guaranteed to work for integer types (though it is
highly likely to work for floating-point types and pointer types).

By the way, if you really do need a 2D array of char (as in your
example) then you can use only one malloc call if you want since char
needs no special alignment.

<snip>
--
Ben.


== 3 of 5 ==
Date: Sun, Feb 28 2010 7:46 am
From: lacos@ludens.elte.hu (Ersek, Laszlo)


In article <a188e3d4-29ff-4a4e-a716-807d837c749e@y17g2000yqd.googlegroups.com>, MBALOVER <mbalover9@gmail.com> writes:
> HI all,
>
> I want to create a 2D dynamic array and then initialize all elements
> with 0.

Ignoring the initialization for a second (because you didn't specify the
element type), I think that the following enables the most flexible
usage, if your rows are all full:

#include <stdlib.h>

type *
get_type2d(size_t rows, size_t cols)
{
return (0u < cols && (size_t)-1 / sizeof(type) / cols >= rows)
? malloc(rows * cols * sizeof(type))
: 0;
}

You would index the allocated array like this:

{
type *arr;

arr = get_type2d(nrows, ncols);
if (0 != arr) {
/* Store ... in array[row][col], conceptually. */
arr[row * ncols + col] = ...;

free(arr);
}
}


This can be generalized for N dimensional arrays. The following function
takes "long unsigned" arguments instead of "size_t", because "size_t"
may be promoted by the default argument promotions, and that doesn't
play very well with va_arg().

#include <stdlib.h>
#include <stdarg.h>

/*
Usage:

get_ndim(el_size, dim_1, dim_2, ..., dim_n, 0LU);

Allocate memory for dim_1 * dim_2 * ... * dim_n elements, each being
of size "el_size". All arguments must be of type "long unsigned". The
variable argument list must be terminated with 0LU.

get_ndim(el_size, 0LU)

allocates a zero-dimensional array (= space for a single element).

The caller is responsible for not passing 0LU as el_size.

The function returns a pointer returned by malloc() (which can be 0),
or 0 if the wanted size (in bytes) cannot be represented in size_t.
*/

void *
get_ndim(long unsigned el_size, ...)
{
size_t max_el,
num_el;
va_list ap;
long unsigned next;

max_el = (size_t)-1 / el_size;
num_el = 1u;

va_start(ap, el_size);
while (0LU != (next = va_arg(ap, long unsigned))
&& max_el / next >= num_el) {
num_el *= next;
}
va_end(ap);

return 0LU == next ? malloc(num_el * el_size) : 0;
}


The access pattern implements the Horner scheme.

http://en.wikipedia.org/wiki/Horner_scheme

An example for the Horner scheme with auto arrays might be:

{
type arr[4][5][6]; /* 120 */

arr[1][2][3] = ...; /* [1 * (5*6) + 2 * (6) + 3], [45] */
}

-->

{
type arr[4 * (5 * (6))]; /* 120 */

arr[(1 * 5 + 2) * 6 + 3] = ...; /* [45] */
}


Thus

/*
If arr denotes the non-null return value of

get_ndim(el_size, dim_1, ... dim_n, 0LU)

that is, arr is conceptually

array[dim_1][dim_2] ... [dim_n]

then the conceptual element with valid subscripts

array[i_1][i_2] ... [i_n]

can be accessed with

arr[get_idx(i_1, dim_2, i_2, ..., dim_n, i_n, 0LU)]

For zero-dimensional arrays, the following is valid:

get_ndim(el_size, 0LU)[get_idx(0LU, 0LU)]

*/

size_t
get_idx(long unsigned outermost_idx, ...)
{
size_t sum;
va_list ap;
long unsigned next_size;

sum = outermost_idx;
va_start(ap, outermost_idx);
while (0LU != (next_size = va_arg(ap, long unsigned))) {
sum = sum * next_size + va_arg(ap, long unsigned);
}

return sum;
}


Usage:

int main(void)
{
double *mtr;

/* allocate 100 4x4 matrices */
mtr = get_ndim(sizeof *mtr, 100LU, 4LU, 4LU, 0LU);
if (0 != mtr) {

/* Set the 59th matrix to 0.0 -- starting at &matrix[58][0][0]. */
size_t base,
idx;
base = get_idx(58LU, 4LU, 0LU, 4LU, 0LU, 0LU);
for (idx = 0u; idx < 16u; ++idx) {
mtr[base + idx] = 0.0;
}

free(mtr);
}
return 0;
}


Cheers,
lacos


== 4 of 5 ==
Date: Sun, Feb 28 2010 7:55 am
From: lacos@ludens.elte.hu (Ersek, Laszlo)


In article <kxoxF7laR3mK@ludens>, lacos@ludens.elte.hu (Ersek, Laszlo) writes:

> size_t
> get_idx(long unsigned outermost_idx, ...)
> {
> size_t sum;
> va_list ap;
> long unsigned next_size;
>
> sum = outermost_idx;
> va_start(ap, outermost_idx);
> while (0LU != (next_size = va_arg(ap, long unsigned))) {
> sum = sum * next_size + va_arg(ap, long unsigned);
> }
>
> return sum;
> }

Obviously, I forgot va_end(ap) before returning.

Sorry,
lacos


== 5 of 5 ==
Date: Sun, Feb 28 2010 8:29 am
From: Malcolm McLean


On Feb 28, 5:46 pm, la...@ludens.elte.hu (Ersek, Laszlo) wrote:
>
> This can be generalized for N dimensional arrays. The following function
> takes "long unsigned" arguments instead of "size_t", because "size_t"
> may be promoted by the default argument promotions, and that doesn't
> play very well with va_arg().
>
Ho ho, hadn't thought of that. Neither, I bet, had the committee.
size_t introduces all sorts of subtle difficulties.

==============================================================================
TOPIC: fputs and fprintf
http://groups.google.com/group/comp.lang.c/t/d665d0bf528f7433?hl=en
==============================================================================

== 1 of 5 ==
Date: Sun, Feb 28 2010 6:10 am
From: "bartc"

"pete" <pfiland@mindspring.com> wrote in message
news:4B8A68FB.12F7@mindspring.com...
> bartc wrote:
>
>> fputs/puts prints a string,
>> while fprintf/printf prints a (format) string
>> *and* any number of other values.
>>
>> But one important difference is that
>> puts writes a newline at the end, while
>> printf requires you to insert the fiddly \n sequence at the end of the
>> string (significant for terrible typists like me,
>> with \ being one of those
>> keys that is in a different place on every keyboard).
>
> Another important difference is that
> puts writes a newline at the end, while fputs doesn't.

No? That's crazy then, why make fputs() and puts() behave differently.

--
Bartc

== 2 of 5 ==
Date: Sun, Feb 28 2010 6:25 am
From: ram@zedat.fu-berlin.de (Stefan Ram)


_JusSx_ <jussx0NOSPAM@gmail.com.invalid> writes:
>I would like to know what differences are between these two
>C functions: *fputs* and *fprintf*.

Remarkable: The answer I would expect to be most often
did not occur at all so far (in the subset of the posters
I read):

fprintf( stderr, userinput );

An attacker who can fully or partially control the contents
of a format string can crash a vulnerable process, view the
contents of the stack, view memory content, or write to an
arbitrary memory location and consequently execute arbitrary
code with the permissions of the vulnerable process [Seacord 05a].

[Seacord 05a] Seacord, Robert C. Secure Coding in C and C++.
Boston, MA: Addison-Wesley, 2005. See
http://www.cert.org/books/secure-coding for news and errata.

http://google.to/search?q=FIO30-C

== 3 of 5 ==
Date: Sun, Feb 28 2010 6:32 am
From: pete


bartc wrote:
>
> "pete" <pfiland@mindspring.com> wrote in message
> news:4B8A68FB.12F7@mindspring.com...
>
>> bartc wrote:
>>
>>> fputs/puts prints a string,
>>> while fprintf/printf prints a (format) string
>>> *and* any number of other values.
>>>
>>> But one important difference is that
>>> puts writes a newline at the end, while
>>> printf requires you to insert the fiddly \n sequence at the end of the
>>> string (significant for terrible typists like me,
>>> with \ being one of those
>>> keys that is in a different place on every keyboard).
>>
>>
>> Another important difference is that
>> puts writes a newline at the end, while fputs doesn't.
>
>
> No? That's crazy then, why make fputs() and puts() behave differently.

I don't know why.

N869
7.19.7.4 The fputs function
Synopsis
[#1]
#include <stdio.h>
int fputs(const char * restrict s,
FILE * restrict stream);
Description
[#2] The fputs function writes the string pointed to by s to
the stream pointed to by stream. The terminating null
character is not written.

--
pete


== 4 of 5 ==
Date: Sun, Feb 28 2010 7:00 am
From: "bartc"


"pete" <pfiland@mindspring.com> wrote in message
news:YoidnbsSb57n4xfWnZ2dnUVZ_uOdnZ2d@earthlink.com...
> bartc wrote:
>>
>> "pete" <pfiland@mindspring.com> wrote in message
>> news:4B8A68FB.12F7@mindspring.com...
>>
>>> bartc wrote:
>>>
>>>> fputs/puts prints a string,
>>>> while fprintf/printf prints a (format) string
>>>> *and* any number of other values.
>>>>
>>>> But one important difference is that
>>>> puts writes a newline at the end, while
>>>> printf requires you to insert the fiddly \n sequence at the end of the
>>>> string (significant for terrible typists like me,
>>>> with \ being one of those
>>>> keys that is in a different place on every keyboard).
>>>
>>>
>>> Another important difference is that
>>> puts writes a newline at the end, while fputs doesn't.
>>
>>
>> No? That's crazy then, why make fputs() and puts() behave differently.
>
> I don't know why.

> [#2] The fputs function writes the string pointed to by s to
> the stream pointed to by stream. The terminating null
> character is not written.

I vaguely remember now fputs/puts had to be compatible with fputs/gets(),
which retain/don't retain a newline character.

Still, you would have expected fputs/puts to do the same thing other than
one takes a file parameter and the other defaults to stdout.

--
Bartc

== 5 of 5 ==
Date: Sun, Feb 28 2010 7:02 am
From: santosh


bartc <bartc@freeuk.com> writes:

>
> "pete" <pfiland@mindspring.com> wrote in message
> news:4B8A68FB.12F7@mindspring.com...
>> bartc wrote:
>>
>>> fputs/puts prints a string,
>>> while fprintf/printf prints a (format) string
>>> *and* any number of other values.
>>>
>>> But one important difference is that
>>> puts writes a newline at the end, while
>>> printf requires you to insert the fiddly \n sequence at the end
>>> of the string (significant for terrible typists like me,
>>> with \ being one of those
>>> keys that is in a different place on every keyboard).
>>
>> Another important difference is that
>> puts writes a newline at the end, while fputs doesn't.
>
> No? That's crazy then, why make fputs() and puts() behave
> differently.

I'd guess that the reason was because while it makes sense to advance
to a newline after printing a line on the standard output (which is
most often a console), it makes less sense in a file.

And also, maybe for symmetry with gets/puts and fgets/fputs
combination. In each pair one reverses the behaviour of the other, in
terms of adding or discarding a newline.

And it's useful to have a function that can write strings without
adding characters on it's own. Sure fputc and fprintf are there, but
while the former is too primitive, the latter adds overhead for just
writing a string.

All the above just my naive guesses:)

==============================================================================
TOPIC: Plan 9's c compiler
http://groups.google.com/group/comp.lang.c/t/110a62f10b04cea0?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Feb 28 2010 6:21 am
From: Dan C


On Sun, 28 Feb 2010 06:00:43 +0000, Seebs wrote:

> On 2010-02-28, Dan C <youmustbejoking@lan.invalid> wrote:
>> Public spanking completed.
>
> Uh, no. Someone pointed out a factual error which he couldn't
> reasonably have known about

Really? He couldn't click the friggin link he claimed was the correct
website, and see immediately that it is not a functioning website?

Yeah, that's not "reasonable" for him to have known that.... Sheesh.

Get a clue.


--
"Ubuntu" -- an African word, meaning "Slackware is too hard for me".
"Bother!" said Pooh, as the condom ripped.
Usenet Improvement Project: http://twovoyagers.com/improve-usenet.org/
Thanks, Obama: http://brandybuck.site40.net/pics/politica/thanks.jpg

==============================================================================
TOPIC: automated sub-string search/replace algorithm...
http://groups.google.com/group/comp.lang.c/t/6c021e75cf801832?hl=en
==============================================================================

== 1 of 1 ==
Date: Sun, Feb 28 2010 6:57 am
From: Ben Bacarisse


"Chris M. Thomasson" <no@spam.invalid> writes:
<snip>
> This is basically the same as my original automated sub-string search:
>
> http://groups.google.com/group/comp.lang.c/browse_frm/thread/38aee559668ee60c
>
>
> except it generates a random exchange string and build an expected
> result string. It then runs the source string through the given
> replacement algorithm and checks to see if everything is Kosher.
>
>
> So far, both Edwards algorithm and mine are passing 10,000,000
> iterations. That's quite a bit of randomly generated data. I cannot
> seem to find any bugs in the algorithms as-is.

This is a useful example: 10 million tests and you have not yet found
the bug! It is in a case that I'd test early rather than later and it
survived from the first to the 12th of the 13 posted versions of the
code. Have you tried your automatic tests on even earlier versions?
It would be interesting see what it can pick up.

> Anyway, I created this because I got sick and tired of manually
> generating test cases!

Hand-picked tests have a lot going for them.

--
Ben.

==============================================================================
TOPIC: Efficency and the standard library
http://groups.google.com/group/comp.lang.c/t/ad9fea19f2f7dd61?hl=en
==============================================================================

== 1 of 2 ==
Date: Sun, Feb 28 2010 7:03 am
From: spinoza1111


On Feb 27, 3:22 am, Keith Thompson <ks...@mib.org> wrote:
> blm...@myrealbox.com <blm...@myrealbox.com> writes:
> > In article <8865e7a2-6b21-4e80-9ba6-eaf563a46...@g28g2000prb.googlegroups.com>,
> >spinoza1111 <spinoza1...@yahoo.com> wrote:
> [more of the same]
>
> > Quoted for Seebs's benefit.  I won't reply.
>
> [...]
>
> Perhaps you could explain to us how re-postingspinoza1111'sravings
> benefits Seebs, or anyone else for that matter.
>
> Eventually you will probably realize that debatingspinoza1111is
> a waste of your own time (which is your to waste) and of the rest
> of our time as well.  Most of his posts here are reponses to other
> posters' response to him.  If people started ignoring him completely,
> he would probably post less, and this newsgroup's signal-to-noise
> ratio would improve vastly.
>
> *Please* stop feeding the troll (or whatever he is; there's been
> some debate about whether he qualifies as a "troll", but the effect
> is the same whether he does or not).

But if I'm not a troll, then why should people stop responding? Even
Seebach has admitted that the discussion I started concerning replace
was very productive for many participants, and I'd suggest that it's
been on topic and useful to people here. Whereas your contribution
seems to have been to tech review Seebach's famous off by one strlen
and miss the bug.

And...I'm not a troll.
>
> --
> Keith Thompson (The_Other_Keith) ks...@mib.org  <http://www.ghoti.net/~kst>
> Nokia
> "We must do something.  This is something.  Therefore, we must do this."
>     -- Antony Jay and Jonathan Lynn, "Yes Minister"

== 2 of 2 ==
Date: Sun, Feb 28 2010 7:13 am
From: spinoza1111


On Feb 27, 11:58 pm, spinoza1111 <spinoza1...@yahoo.com> wrote:
> On Feb 27, 1:52 am, blm...@myrealbox.com <blm...@myrealbox.com> wrote:
>
>
>
>
>
> > In article <0e861416-2f69-455d-a61e-e9878eeab...@y7g2000prc.googlegroups.com>,
>
> >spinoza1111 <spinoza1...@yahoo.com> wrote:
> > > On Feb 25, 10:12 pm, Walter Banks <wal...@bytecraft.com> wrote:
> > > > spinoza1111wrote:
>
> > [ snip ]
>
> > > > Results are in the middle of the pack not the stuff of a A+.
>
> > > > w..
>
> > > Oh gee, this was Walter. If anything I said (including my poem)
> > > implies that my opinion of blm is lower, I withdraw it. I already had
> > > a low opinion of Walter.
>
> > Which poem was that ....  (I have to say that I usually skip your
> > verse.)  
>
> Of course you do, dear Ms Massingill,
> Of course you do, for we live in an age of songs of the doomed
> Tuneless dirges are all you hear
> The music of language, what you fear.

This was poorly written and unnecessarily offensive on my part, as
opposed when it is necessary to be offensive to the truly offensive. I
apologize for this.
>
> It was where I replied to Walter's saying I'm in the middle of the
> pack. Got my goat, since I wouldn't be in the middle of any pack that
> would have me. I am either way ahead or light years behind any pack
> here.
>
>
>
>
>
> > --
> > B. L. Massingill
> > ObDisclaimer:  I don't speak for my employers; they return the favor.

==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.c"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.c?hl=en

To unsubscribe from this group, send email to comp.lang.c+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.c/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate