-
Array size
I need the following code to return a string of character stored in
array and also return the size of the array. I want to do it without
using pointers and so far have the character storing working fine, it's
just that I can't really think of a way to return the number of
characters in the array. Anyone help me out?
Code:
int inputPhrase()
{
char msg[characters], ch;
int i = 0;
int n = 5;
while ((ch = getchar()) != '\n')
{
msg[i++] = ch;
}
msg[i] = '\0'; /* prevents garbage from being place at end of array
output */
i = 0;
while (msg[i] != '\0')
{
printf("%c", msg[i++]);
}
return n;
}
int main()
{
inputPhrase();
int size = inputPhrase();
printf("%d\n", size);
return 0;
}
Ignore the n = 5; I just used that to make sure that main was
outputting n correctly, obviously, n needs to be originally set to 0
then incremented up to the appropriate number of characters in the
array.
-
Well, if you're really using an array, you'd likely have to define its size at compile time, so its value would be rather trivial. And the rest might be trimmed down to this if you don't need to store the string.
Code:
int inputPhrase(void)
{
int i = 0;
while ( getchar() != '\n' )
{
i++;
}
return i;
}
You can only return one value from a function.
-
I used #define to set characters to 30, so the msg array has a maximum size of 30, but if its less, I need the function to return the size of the array. As it is now, the function takes a string of chars and stores them, then returns them. This is something that's gotta be there too.
-
It is really best handled using passed parameters.
[edit]Bad example. Better one to follow.
Code:
#include <stdio.h>
int inputPhrase(char *s, int size)
{
int ch, i = 0;
while ( i < size - 1 )
{
int ch = getchar();
if ( ch == '\n' || ch == EOF )
{
break;
}
s[i++] = ch;
}
s[i] = '\0';
return i;
}
int main(void)
{
char text[30];
int size = sizeof text / sizeof *text;
int count = inputPhrase(text, size);
printf("text[%d] = \"%s\" : %d characters.\n", size, text, count);
return 0;
}
/* my output
Hello world
text[30] = "Hello world" : 11 characters.
The quick brown fox jumps over the lazy dog.
text[30] = "The quick brown fox jumps ove" : 29 characters.
*/
-
Don't really understand pointers and I don't want to use them in this situation unless they're a last resort, any other advice on what I could do?
-
There are worse choices: global variables, returning a structure, etc. I'd say try to learn this easy way.