Deutsch   English   Français   Italiano  
<87zfovwsq6.fsf@bsb.me.uk>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!weretis.net!feeder8.news.weretis.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Ben Bacarisse <ben@bsb.me.uk>
Newsgroups: comp.lang.c
Subject: Re: is it possible to point to a slice of an array without malloc or VLAs?
Date: Thu, 29 Aug 2024 11:04:01 +0100
Organization: A noiseless patient Spider
Lines: 43
Message-ID: <87zfovwsq6.fsf@bsb.me.uk>
References: <NS2dnaQtUKseUVP7nZ2dnZfqn_WdnZ2d@brightview.co.uk>
	<vamm7j$3d74u$1@dont-email.me>
	<4Z6dnTcuH5c_tU37nZ2dnZfqn_qlxKTP@brightview.co.uk>
MIME-Version: 1.0
Content-Type: text/plain
Injection-Date: Thu, 29 Aug 2024 12:04:01 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="fea14ca971f37fc10e006db08518a19f";
	logging-data="4129172"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1/6J3LuVWgROgjO34dkX1wqjr6W0nhb16o="
User-Agent: Gnus/5.13 (Gnus v5.13)
Cancel-Lock: sha1:2z4KHz1VvROZW75VDefoPuOux7I=
	sha1:et+N6nvYiXM1rff9TTscay4gQjg=
X-BSB-Auth: 1.14f52f4f4a007982e44d.20240829110401BST.87zfovwsq6.fsf@bsb.me.uk
Bytes: 2491

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.