what is the equivalent of UBOUND in C++?
Printable View
what is the equivalent of UBOUND in C++?
try this :
http://161.58.186.97/showthread.php?...ghlight=ubound
:)
Try this.
Code:#define UBound(n) sizeof(n) / sizeof(n[0]);
// Usage:
int myArray[35];
cout << UBound(myArray);
what does the UBOUND function do?
ti give the last number in array. if the array have 35 it will giev 35.
Exemple (in vb )
For i = 0 to 100
msgbox i
next i
ubound(i) = 100
What about plain C?Quote:
Originally posted by
Try this.
Code:#define UBound(n) sizeof(n) / sizeof(n[0]);
// Usage:
int myArray[35];
cout << UBound(myArray);
#define isn't to work on pre-compiler only? I think this wouldn't work in plain C...
Can someone help me here? :D
Quote:
I think this wouldn't work in plain C...
hummm
macro work in C and C++
No, it didn't work on plain C.
But I got how to do it.
for 1 dimensional array
for 2 dimensional arrayCode:int arr[10]
printf("%d", sizeof(arr) / sizeof(int))
and it goes on...Code:int arr[10][20]
printf("%d", (sizeof(arr[0]) / sizeof(int)) ) // last part
printf("%d", (sizeof(arr) / sizeof(int)) / (sizeof(arr[0]) / sizeof(int)) ) // semi-last part
Hmmm... How could i make this a function that accept any kind of variable?
And, even harder, how could I make this to accept any # of dimensions?Code:int ubound (? *arr) {
return(sizeof(arr) / sizeof(?));
}
Don't bother. In C you know how big it is anyway so I fail to see the problem...
Wrong again.
Take a look on "two-dimensional dynamical array of char" post right besdie this one.
I ned an UBound here...
And, on that char arr I created the UBound I mentioned here is not working (sizeof(arr) / sizeof(char)).
But why? In C, to make a 2D array, you have to know the sizes of both dimensions, either statically or dynamically.
Whatever method of creation, you must know the size beforehand, right? You can just cache the size and use it later...
There is no way of determining the size of an array if you loose the original values. There is _msize, but it's non-standard and works only under special circumstances.
parksie is right. I never saw any reason to determine the size of an array after I created it. After all, you're in control of your code.
I'm not sure about this.
In this case I just didn't want to make a global variable to store the array size...
But, I guess I can think in a way on C where u create an array without knowing its size...
But maybe you two are right.
Anyway, even on VB, what would be the use of UBOUND, thinking that way?
In C, functions that take an array as parameter are declared like this:
returntype name(type *arrray, int sizeofarray);
Whereas in VB they simply are
Sub name(array As whatever)
since the size of the array can be obtained using UBound.
Not that it matters, C arrays are still way faster, see the dynamic char array thread, the STRANGEARRAY is very similar to the VB array.
You never have a global size variable for not-global arrays, the size variable is local and passed along with the array.
Ok, but that was not a good example of needing to use UBound on VB.
I though u at least would tell about databases...
You just said that you do that VB call just because UBound exists, but I asked about why should UBound exist, at first.
It exists because it's there. The internal data structure of a VB array has a member that holds the size, so why not expose it?
C/C++ database functions usually return the number of entries the array has.
Ok, this is first thing i dont like about C then... :D
But you think would be possible create an structure to define arrays, any size of arrays, get with them their size?
Well, anyway, why "sizeof" doesn't work?
I though sizeof would get all size ocuped on memory by that variable or kind of variable.
Those are 2 different questions. :)
sizeof() is done at compile time. Yes, it is possible to make a struct that can hold the size, this is what the c++ library "vector" class does :)
Try this and (perhaps) be surprised:Code:#include <stdio.h>
#include <stdlib.h>
int main(void) {
int blah;
int foo[] = { 1, 2, 3, 4, 5 };
int *bar = malloc(sizeof(int) * 5);
printf("sizeof(blah) = %d\n", sizeof(blah));
printf("sizeof(foo) = %d\n", sizeof(foo));
printf("sizeof(bar) = %d\n", sizeof(bar));
free(bar);
return 0;
}
I tried it, and, crap!
Is there some similar to sizeof that do it at run time?Quote:
sizeof(blah) = 4
sizeof(foo) = 20
sizeof(bar) = 4
And is vector on plain C too? Did'nt know that class... :D
Do you see *why* you've got different numbers?
For runtime, nope. But since you *always* know without fail how big it was, since you either created it of that size, or the API you're using supplied you with the size.
And no, there's no vector in plain C (no templates, classes, etc). I did have some code to do a vector in C somewhere but I'd have to dig it out.
About the vector code, I think Corned posted it on my other topic. I must check if it is that at really, cause I didn't read it yet. :P
About the different numbers, in fact, even considering it is compile time, no, I still don't know why they are different.
Look, right in the code it is explicit the size of bar. It is int (whici is 4) multiplied by 5. That should mean 20! Even before running the program...
Right. You just need to look directly at the types. In this case...Code:int blah;
int foo[] = { 1, 2, 3, 4, 5 };
int *bar = malloc(sizeof(int) * 5);
blah - int. 4 bytes of storage.
foo - array of 5 ints, which is 5 * 4. This is known by the compiler, and included directly into the stack, thus sizeof gives 20.
bar - pointer to int, which on a 32-bit machine is 4 bytes. It contains the memory location of where there is space allocated for 5 integers. Not the integers themselves. Sizeof takes the size of the pointer and returns it.
This is the main confusing thing in C, the differences between pointers and arrays. In fact, you could do bar = foo, and it would work properly. But the sizes would still be different. Arrays transparently decompose into pointers with almost any operation.
Oh, and the call to malloc() the compiler knows it's passing 20 to it, but as far as it's concerned, it's just another function...
Alright cut it out here
try this and see what happens:
Well anyways, what is happening here is that a pointer (or a reference) in C AND C++ will occupy 4bytes of memory. a char is 1 byte of memory, sizeof returns the bytes in memory not the quantity. in case of pointers they are ALWAYS 4 bytes no matter what type of pointer it is...Code:
char a = 'A';
int *b = &a;
char &c = *b;
int d[] = {100,20,15,16,99,0,5,9};
char e[3] = {0};
printf ("sizeof(int) : %d\n", sizeof(int)); // 4
printf ("sizeof(a) : %d\n", sizeof(a)); // 1
printf ("sizeof(b) : %d\n", sizeof(b)); // 4
printf ("sizeof(c) : %d\n", sizeof(c)); // 1 (??)
printf ("sizeof(d) : %d\n", sizeof(d)); // 4 * 8
printf ("sizeof(e) : %d\n", sizeof(e)); // 1 * 3
Have fun learning, gottta go! Bye
4 bytes on a 32-bit system ;)
8 bytes on 64-bit, and various other bizarre formats...
Got what u meant. Thanks. :)Quote:
Originally posted by parksie
[B]
bar - pointer to int, which on a 32-bit machine is 4 bytes. It contains the memory location of where there is space allocated for 5 integers. Not the integers themselves. Sizeof takes the size of the pointer and returns it.
Agree. :DQuote:
Originally posted by parksie
This is the main confusing thing in C, the differences between pointers and arrays.
That's another thing which helps me confuse things...Quote:
Originally posted by parksie
Oh, and the call to malloc() the compiler knows it's passing 20 to it, but as far as it's concerned, it's just another function...
But, well, malloc is getting it right because sizeof(int) * 5 is 20 at really, but sizeof(bar) * 5 isn't... If I understood it well.
I'll try MoMad example soon, can't do it rite now. :P
Maybe it clarify something, and I'll do some more tests too...
I still wish to make some way to get the array size. :)
if you really want to go crazy with array sizes, why dont u just use std::string ??
or something like that... erm, maybe i should give u more details? Anyways, what it looks like is that u want a way to get the ubound of an array, listen to what the ppl b4 u had to say about it, its unnecesary!! You dont need it, and if you really, really, really, really, really, really, really, really, really, (and REALLLLLLLYYYYY) needed it, you can just emulate it urself!!Code:#include <iostream>
#include <string>
using namespace std;
int main (void ) {
string str1;
str1 = "Hello World!";
cout << "Str1.length == " << str1.length << endl;
}
Like this:
I would'a wrote something fancy smanshy but i just dont have the time to go in too deep with this... if you really think about it, at some point or another you will HAVE TO know the size of the array. Make a class if you want some sort of a dynamic array or use the stl, it has loads of things like vector, list, map, etc...PHP Code:
struct ArrObj {
// uncomment the following if ur using c++ compiler
// ArrObj () : pData(0), iSize(0) {}
// ~ArrObj () { if (pData) free(pData); pData=0; iSize=0; }
void * pData;
int iSize;
}
// ... now u can put it to use
// ...
ArrObj myArray;
myArray.iSize = 100;
myArray.pData = malloc (myArray.iSize);
If you wanna see a simple work around using c++ lemme know and ill make it quick. If you are thinking of c, forget about it!! There is nothing that c has which c++ doesnt have! C++ is an advanced version of c, like version 2 with tons more improvements and new stuff!
He wants plain C I think, MoMad. Therefore the string class cannot be used (and he should understand pointers anyway), and the first example won't compiler because C doesn't know references.
Yea, also most systems these days are 32bit (winNT and win9x).. i dont know about XP so every windows besides XP is 32bits (if im wrong, dont hesitate to correct me)
So pointers are always sizeof(int). No matter what. Because on 32 bit systems an int is 4bytes and on 64 bit it is 8bytes. See what i mean.
Enough about sizes, heres the real deal:
A Pointer is just an integer that holds the "memory address" of a variable in memory (it doesnt even have to be a variable, it could be anything). So a pointer can hold a memory location to ANYTHING.
In C AND C++ arrays are just a pointer to the first element of the array.
Thats all folks, there u go a complete string/array/pointer tutorial :)PHP Code:
// Array
int i =0;
char stringarray[50];
char * ptrstrarray = stringarray;
// the first element of the array is stringarray[0]
char * pstrarray5th = &stringarray[4];
// you can do arithmatic on the pointers
void * ptrvar = pstrarray5th;
// initialize the array
for (i = 0; i < 50; i++) {
stringarray[i] = i*2+1;
}
stringarray[49] = 0;
ptrvar++;
ptrvar += 10*sizeof(stringarray[0]);
// ptrvar is on the 16th member of the array now
ptrvar--;
// 15th now
for (i = 0; i < 15; i++) {
ptrvar--;
}
// now ptrvar is the same as ptrstrarray
if (ptrvar == ptrstrarray) {
printf ("%p == %p\n\nTHEY ARE THE SAME!\n", ptrvar, ptrstrarray);
}
// you can also get an array using this notation
printf ("The 15th element of the array is %d", (int) *(stringarray+15));
// note i casted it to int because %d in printf uses ints not char
// also using %c will give a weird character instead of the number
// now finaly, you know that arrays are really pointers in disguise
// and that pointers are really "integers that hold memory addresses"
// last but not least, here is a whole bunch of other examples of
// pointers at work (for ur edutainment).
// u can manually point to a specific locale
ptrvar = 0x00FFF7;
// u can go above and beyond the boundaries of ur "allowed" memory space
// 10 spaces before and after (could cause program to crash)
ptrvar = (stringarray)-10;
ptrvar = (stringarray)+60;
// pointers can point to functions
// main is a function incase u didnt know
// pointer to main function
ptrvar = main;
// u can use a function that has any number of parameters
// e.g. strcmp
ptrvar = strcmp;
// to call the function or to see the variable the pointer
// points to, just dereference the pointer
// dereference means that u put a start (*) infront of the variable
// for functions, you must enclose with () or the operator
// precedence rules will cause u problems; always use () just
// to be safe!
i = (*ptrvar) (stringarray+15, stringarray[15]);
printf ("strcmp(%s,%s) == %d", stringarray+15, stringarray[15], i);
Um, on the 64-bit systems I've used, int is still 4 bytes. long sometimes becomes 8 bytes.
XP is 32-bit, yes. Everything NT and 9x is 32-bit, Win 3.11 and below is 16-bit.
Yes, that I knew. It's what my teacher said, few months ago. But it doesnt explain the difference that really happens between pointers and arrays on plain C, just like it exists on that parksie example.Quote:
Originally posted by MoMad
A Pointer is just an integer that holds the "memory address" of a variable in memory (it doesnt even have to be a variable, it could be anything). So a pointer can hold a memory location to ANYTHING.
In C AND C++ arrays are just a pointer to the first element of the array.
Anyway, Corned is right, I want plain C. I won't go to learn C++ before I learn all about plain C bases.
And I won't say anything else till I can read all MoMad posted and test what is posted here already, and something more.
Hold, and you ppl will see new questions here. :D
Thanks for u 3, parksie, CornedBee and MoMad. :P
You don't actually need C to learn C++, you realise.
In fact, if your plan is to learn C++, learn that. Don't come through C first. No matter what your (brain-dead?) teachers may say, it's unnecessary.
Ya, but my classes are all about plain C.
If I get C++ now, I may make some mistakes not good for my grade. :)
So, since I'm going to do all plain C now, I wish to get it right first.
What system is that? I can only guess linux/unix... or apple... but hey, i dont know much outside the windows fammily so yeah, tell me! Also, thx for clarifying the xp, for some reason i thought it was gonna be microsoft's "upgrade" windows... but when i saw it, it looked just like the jump from 95 to 98. Fancy smanshy!! lol.Quote:
Originally posted by parksie
Um, on the 64-bit systems I've used, int is still 4 bytes. long sometimes becomes 8 bytes.
One more thing I forgot to mention earlier, a function name in c/c++ is a pointer to the memory where the function's code is at. So in my previous example, i said:
its just the same as saying:PHP Code:ptrvar = main;
Also, use void* if you dont know the TYPE of pointer you have. And use the cast operator () to cast from one type to another, on pointers casting is unnecesary and is good practice for understanding the code/ making the compiler/debuger 's work much easier.PHP Code:// if main is at memory location 0x007F25;
ptrvar = 0x007F25;
And finally, to see what the variable actually holds, (you will have to know what type it is :)) just dereference it like this:
note that the ++ knows how many bytes to increment by when you cast before incrementing/decrementing. the default is just 1 byte if the type is void* but if the type is otherwise, it will be sizeof(<vartype>) where <vartype> is the type of variable you casted the pointer to.PHP Code:// the () are not required but just to be safe about the order and precedence stuff
char char_at_ptrvar_0 = (*ptrvar);
char char_at_ptrvar_1 = (*(ptrvar+1));
char char_at_ptrvar_7 = (*(ptrvar+7));
// ...
// also one more thing, you can cast and dereference
// assume that ptrvar points to an array of char and you want
// to get the first 4 bytes into an int and next 2 bytes into a short
int last_4_bytes_of_array = (int) * (((int *) ptrvar)++);
short next_2_bytes_of_array = (short) * (((short *) ptrvar)++);
Thats a wrap!
BTW: It is because of such direct memory access that you often hear the quote:
Quote:
C makes it easy for you to shoot yourself in the foot; but C++ makes it harder and lets you blow your whole leg off when you do
<snip> (or something like that)
- Anon
Anon? It was Bjarne himself ;)
MoMad -- 64-bit Irix 6.5 system (Silicon Graphics) :D
I dont know so I said Anon (Annonymous) lol. Who's Bjarne anyways? I never heard of...
YOU DON'T KNOW WHO BJARNE IS?!?!?!?!?!
/me slaps MoMad vigorously with a small haddock
Bjarne Stroustrup only invented C++ ;)
I thought he was a tennis player.
OOoooohhhhhh
..oo0OQO0oo..
Ow! that hurt, stop it!
See I thought there where like more than 1 C++ inventers, i mean really... And there where 2 C inventers.. Stroustrup And some other guy. I didnt know who bjarne was cuz in most books they only use his last name!! haHAHAHAH
C was Brian Kernighan and Dennis Ritchie (the K&R you might have heard of :D). C++ was all Stroustrup.