Re: is it possible to point to a slice of an array without malloc or VLAs?

Liste des GroupesRevenir à l c 
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.c
Date : 29. Aug 2024, 12: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.

Date Sujet#  Auteur
28 Aug 24 * is it possible to point to a slice of an array without malloc or VLAs?8Mark Summerfield
28 Aug 24 +* Re: is it possible to point to a slice of an array without malloc or VLAs?3Phil Ashby
29 Aug 24 i`* Re: is it possible to point to a slice of an array without malloc or VLAs?2Mark Summerfield
29 Aug 24 i `- Re: is it possible to point to a slice of an array without malloc or VLAs?1Ben Bacarisse
28 Aug 24 +- Re: is it possible to point to a slice of an array without malloc or VLAs?1Stefan Ram
28 Aug 24 `* Re: is it possible to point to a slice of an array without malloc or VLAs?3Blue-Maned_Hawk
28 Aug 24  +- Re: is it possible to point to a slice of an array without malloc or VLAs?1Ben Bacarisse
28 Aug 24  `- Re: is it possible to point to a slice of an array without malloc or VLAs?1Tim Rentsch

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal