-
Why O why, strlen?
Why is it that strlen returns the number of chars currently in the string, and not the actual declared size of the array?
When I first started using strlen, I loved this feature, since when used to control a loop it avoids useless iteration. Now I want something that will tell me the declared size of the array, regardless of how many chars are currently in it...
And since I'm on the subject, how might one dinamically allocate a string of certain size? I know that you cannot place a variable in the [array_size] area, only a straight number else a #defined real number. So how?
-
lol
Um, duh. You declared it, why don't you know it...and if you don't know it for some odd reason, what's wrong with a while loop?
while(array[x] != '\0')
x++;
x++; //so you get the very last char (for the '\0')
dynamic allocation is simple...
char *array;
array = (char *)malloc(size);
where size is how big you want it...
hth
-
That will only tell him what strlen() would. If you're working with an array and not a pointer then
yourarray/yourarray[0];
will give you the size of the array.
-
ohh...*smacks himself*
no...it'd give him one+strlen :)...I haven't programmed in 3 days! gimme a break!
-
O.K.
Here's the scoop:
I'm trying to write a function that emulates fgets(), but is used like gets()...
-
>>I haven't programmed in 3 days! gimme a break!<<
That's no excuse. It should be longer than a week before you forget anything :) .
-
Code:
#include <stdio.h>
#include <string.h>
char* newgets(char* buffer,int num)
{
int i;
fgets(buffer,num,stdin);
i=strlen(buffer)-1;
if (buffer[i]=='\n') buffer[i]='\0';
return buffer;
}
-
Code:
#include <stdio.h>
#define MYGETS_BASESIZE 8
char *mygets(char *buffer)
{
int s=0, l=0;
do /* read a long line in small pieces */
{
s+=MYGETS_BASESIZE;
buffer=(char *)realloc(buffer, s);
fgets(&buffer[l], s-l, stdin);
l+=strlen(&buffer[l]);
}
while(buffer[l-1]!='\n');
buffer[l-1]='\0';
buffer=(char *)realloc(buffer, l);
return buffer;
}
main()
{
char *input;
/* read first line */
input=mygets(NULL);
printf("first line: %s\n", input);
/* read another line, 'overwriting' the first line */
input=mygets(input);
printf("second line: %s\n", input);
/* free malloc'ed memory */
free(input);
}
The mygets function automatically adjusts the string to the right size. This also means that you cannot use a static buffer as argument to this function, and that you are responsible for freeing the allocated memory!
-
Wowsers! Ya didn't have to write it out for me!
But no complaints!
Thanks Alex, thanks Stony!
-
To get the actual declared size of the array you can use
sizeof(arrayname);
sizeof returns the actual declared array size regardless of the number of characters it contains.
Hope that solves your original query. :)
-Goran.
-
and....
sizeof(arrayname)/sizeof(arrayname[0]) will give you the number of elements in the array regardless of the data type the array contains...
mxr
-