Sujet : Re: is it possible to point to a slice of an array without malloc or VLAs?
De : ben (at) *nospam* bsb.me.uk (Ben Bacarisse)
Groupes : comp.lang.cDate : 29. Aug 2024, 11:04:01
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <87zfovwsq6.fsf@bsb.me.uk>
References : 1 2 3
User-Agent : Gnus/5.13 (Gnus v5.13)
Mark Summerfield <
mark@qtrac.eu> writes:
On Wed, 28 Aug 2024 09:13:39 +0100, Phil Ashby wrote:
[snip]
To answer the specific question, I would use pointer arithmetic,
provided there is no intention to modify values, ie:
char **slice = argv + config->optind;
thus slice now points at the appropriate part of argv and can be indexed
or dereferenced / incremented to access elements.
[snip]
>
Thank you, that works great. I now do that plus store the slice's size using:
argc - optind
>
I tried to get the size using
>
#define ARRAYSIZE(a) (&(a)[1] - (a))
The difference between a pointer to the second element of an array and a
pointer to the first will always be 1.
Another way to look at this is to expand the expression.
a[1] means *(a+1)
&a[1] means &*(a+1)
&*(a+1) is the same as a+1 (barring some details; see 6.5.3.2 p3)
&a[1] - a means a+1 - a or just 1
char **folders = argv + optind;
int num_folders = argc - optind;
int size = ARRAYSIZE(folders);
printf("%d %d\n", num_folders, size);
>
but size was always 1.
Another fact that might help you is that the argv array will have a null
pointer as it's last element so you may not need to remember the length
of the slice since it is the tail slice of a null-terminated array.
-- Ben.