Re: Help With Arrays
- From: "Malcolm" <regniztar@xxxxxxxxxxxxxx>
- Date: Sat, 30 Apr 2005 22:59:53 +0000 (UTC)
"Craig" <NOSPAMcarvinabuser@xxxxxxxxxxxxxx> wrote
> Hello friends at comp.lang.c,
>
> I'm reading from a socket descriptor and copying the data to a buffer
> using:
>
> char buffer[MAXVALUE];
> .
> .
> nread = read(newSd, line, MAXVALUE);
>
> The string to be copied to the buffer is of varying size, so what I'd like
> to know is if there's a way to copy the data, without having to specify a
> max value, making the size of the string the same size as the array.
>
(IFYM size of the array same as size of the string)
As you probably know, a C string is a NUL-terminarted list of characters.
In C, an array must have a size known at runtime. If the string is smaller
than the array, you have no problem (the NUL gives the length). if it is
larger, you will overflow.
The way round this is to use malloc(). When you know the size of the string,
call malloc() with the length plus one for the NUL. This means that "buffer"
must be a pointer rather than an array. You cna also use realloc() to grow
and shrink the buffer as required.
.
- Prev by Date: Re: a few doubts!
- Next by Date: Re: a few doubts!
- Previous by thread: Re: a few doubts!
- Next by thread: Re: Help With Arrays
- Index(es):
Relevant Pages
|