Shoutbox

C - vectors - Printable Version

-Shoutbox (https://shoutbox.menthix.net)
+-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58)
+--- Forum: Skype & Technology (/forumdisplay.php?fid=9)
+---- Forum: Tech Talk (/forumdisplay.php?fid=17)
+----- Thread: C - vectors (/showthread.php?tid=84331)

C - vectors by Chancer on 06-15-2008 at 01:53 AM

Quick question.

If I create a vector and read from the keyboard:

code:
char word[20];
scanf ("%s", word);

How can I know/discover the number of elements added into the vector?
RE: C - vectors by Mnjul on 06-15-2008 at 11:12 AM

Use strlen() ? Include <string.h> .

Anyway, it's an array, not vector; because there's a C++ STL type called vector :p


RE: C - vectors by Chancer on 06-15-2008 at 08:34 PM

quote:
Originally posted by Mnjul
Use strlen() ? Include <string.h> .

Anyway, it's an array, not vector; because there's a C++ STL type called vector :p
Nice. That's what I was looking for.

My teachers call it 'vector'. In Portuguese, obviously. So it may be a translation issue or something.


RE: C - vectors by TheSteve on 06-16-2008 at 05:28 AM

Keep in mind that strlen() will only work if your string has a null character at the end.  In the case of scanf, it should be null terminated as long as the user doesn't input more than 19 characters.   (more than that and the program could crash or just act strangely of course.)


quote:
Originally posted by RaceProUK
quote:
Originally posted by Chancer
code:
char word[20];
scanf ("%s", word);

Bye-bye program :P
Not always.  Depending on how much data is inputed in to the program, and how much other data is on the stack, it could just overwrite the other variables in the function. Even if the data size does exceed the current stack frame, there's always going to be a chance that the return address is going to be overwritten by a random, but valid memory address, which would cause a very interesting situation to debug. :P
RE: C - vectors by Chancer on 06-19-2008 at 01:57 AM

quote:
Originally posted by TheSteve
Keep in mind that strlen() will only work if your string has a null character at the end.  In the case of scanf, it should be null terminated as long as the user doesn't input more than 19 characters.   (more than that and the program could crash or just act strangely of course.)
Yes, of course.
If I was taugth right, the last thing that '%s' adds to the sequence is '\0'. So this is the 'null character' you mentioned.