Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #168591

string to size_t

From Oğuz <oguzismailuysal@gmail.com>
Newsgroups comp.lang.c
Subject string to size_t
Date 2022-12-19 14:15 +0300
Organization A noiseless patient Spider
Message-ID <tnph4t$8ind$1@dont-email.me> (permalink)

Show all headers | View raw


I wrote the function below for converting a string to size_t without 
manually calculating its value digit by digit. It first converts the 
string to intmax_t, and if the conversion fails due to a range error and 
SIZE_MAX doesn't fit into an intmax_t, it tries again with uintmax_t. In 
both cases, if the result is less than zero it fails. And on success it 
populates *result with the result.

It works on my machine and a couple others I tried, but I'm not sure if 
it's good C, or a good idea at all. What do you think about it?

int
strtosize(const char *nptr, char **endptr, int base, size_t *result) {
	intmax_t s;
	uintmax_t u;

	errno = 0;
	s = strtoimax(nptr, endptr, base);

	if (errno == 0 && s >= 0 && s <= SIZE_MAX) {
		*result = s;
		return 1;
	}

#if SIZE_MAX > INTMAX_MAX
	if (errno == ERANGE && s == INTMAX_MAX) {
		errno = 0;
		u = strtoumax(nptr, endptr, base);

		if (errno == 0 && u <= SIZE_MAX) {
			*result = u;
			return 1;
		}
	}
#endif

	if (errno == 0)
		errno = ERANGE;

	return 0;
}

Back to comp.lang.c | Previous | NextNext in thread | Find similar | Unroll thread


Thread

string to size_t Oğuz <oguzismailuysal@gmail.com> - 2022-12-19 14:15 +0300
  Re: string to size_t Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2022-12-19 09:59 -0800
    Re: string to size_t Oğuz <oguzismailuysal@gmail.com> - 2022-12-19 21:34 +0300
      Re: string to size_t Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2022-12-19 10:49 -0800
        Re: string to size_t Richard Damon <Richard@Damon-Family.org> - 2022-12-19 14:29 -0500
          Re: string to size_t Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2022-12-19 12:05 -0800
    Re: string to size_t scott@slp53.sl.home (Scott Lurndal) - 2022-12-19 18:40 +0000
      Re: string to size_t Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2022-12-19 12:07 -0800
        Re: string to size_t scott@slp53.sl.home (Scott Lurndal) - 2022-12-19 20:31 +0000
      Re: string to size_t Tony Oliver <guinness.tony@gmail.com> - 2022-12-19 16:33 -0800
    Re: string to size_t Tim Rentsch <tr.17687@z991.linuxsc.com> - 2022-12-19 11:20 -0800
  Re: string to size_t Ben Bacarisse <ben.usenet@bsb.me.uk> - 2022-12-19 22:16 +0000

csiph-web