Tuesday, July 14, 2009

Declaring an array in C++?

Two (related) questions:





What's the difference between





public int[ ] sourceType;





in a header file, and





int sourceType[ ];





in the body of a program?





**** **** **** **** **** **** ****


The program I have is giving me an index out of bounds error when iSource (below) becomes 21. The only place that sourceType is mentioned is in a header file, where it is declared as public int[ ] sourceType. A size is never specified for it (anywhere in the program). Does anyone know why the program is acting as if the array has a size limit of 21 (indexes 0-20) when no size is ever declared?





for (iSource = 1; iSource %26lt;= es. numSources; iSource++)


{





es.sourceType [iSource] = 32;


}

Declaring an array in C++?
Those two variables are completely independent of each other.





You didn't provide the architecture, but I'm guessing that the one from the header file is a field in a class and the second one is inside a function somewhere as a local variable.





I'm guessing that the sourceType referenced in the for loop is the field one (public int[] sourceType) since it's being dot dereferenced (es.sourceType).





The reason you're getting the out-of-bounds error is because es.numSources is %26gt;= 21.





I've got a feeling that loop should read:


for (iSource = 0; iSource %26lt; es.numSources; ++iSource)


{


es.sourceType[iSource] = 32;


}





If the loop is correct then investigate why es.numSources (probably declared in a header as: public int numSources;) is larger than it should be.





Hope that helps.
Reply:All right, this code makes very little sense to me, but I'm going to give you a few of my thoughts on question 2.





1. es.numSources... That dot operator on es makes this look more like C# code than C++. Nonetheless since C++ does support classes, I'll assume C++ here.





2. Any C/C++ compiler I've ever used has required a size/initialization of the array before you use it. So at some point, this array IS being given a size.





3. In your typical for loop iterating through an array, you don't want your test to be "less than or equal to," just "less than."


Reason:


Array indexes start at 0. So in an array of 5 objects, you would have object[0], object[1], ... object[4].


object[5] is in fact the *sixth* object, and that's not possible in an array of size 5.





4. Your test case indicates you are looping until you've gone through all of es's integers. Later, in the loop code, you are attempting to access es.sourceType's objects. These are not the same. Unless you know with absolute certainty that the size of es.sourceType matches the size of es, you cannot hope to accomplish anything with this code.





So to summarize, try changing your code to read:





for (iSource = 0; iSource %26lt; es.numSources; iSource++)


{


es[iSource] = 32;


}





*OR*





for (iSource = 0; iSource %26lt; es.sourceType.numSources; iSource ++)


{


es.sourceType[iSource] = 32;


}





... and see what happens.


What is the dev c++ solution, that has an array max of 40 elements......?

what is the dev c++ solution, that has an array max of 40 elements..the input should be from 0 to 9 only....and output the number according to its place value,, it shoud have a comma for each of the proper place value, the input should be outputed from up to down,,,,





here is the output:





Enter size: 4


4


0


9


6


Result: 4,096 (it should contain the comma (","),if it is greater than hundreds that pertains to its proper place value)





another example:


Enter size: 3


1


2


3


result: 123





another ex. hehehe:


Enter size:7


1


2


3


4


5


6


7


result: 1,234,567

What is the dev c++ solution, that has an array max of 40 elements......?
Hi Edrew,


Here is the MORE ACCURATE SOLUTION to your problem.


It will remove the shortcomings of the solution given by dear "iyiogrenci" just above my answer..








main()


{


int a[40];


int i,r,c,n;





printf("Enter total elements to be entered (1-40) : ");


scanf("%d",%26amp;n);





for(i=1;i%26lt;=n;i++)


{


printf("Enter element a[ %d ]=",i);


scanf("%d",%26amp;a[i]);


}





printf("\n\n");





if(n%26lt;=3)


for(i=1;i%26lt;=n;i++)


printf("%d",a[i]);


else


{


r=n % 3;


if (r != 0)


{


for (i=1;i%26lt;=r;i++)


{


printf("%d",a[i]);


}


printf(",");


}





c=n/3;





for(i=1;i%26lt;=c;i++)


{printf("%d%d%d",a[r+1],a[r+2],a[r+3])...


r=r+3;


if(i!=c)


printf(",");


}


}


}





.


.
Reply:#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





main() {


int a[40];


int x,k,i,r,c,n;





printf("n=%",n);


scanf("%d",%26amp;n);





for(x=1;x%26lt;=n;x++) {


printf("a[ %d ]=",x);


scanf("%d",%26amp;a[x]);





}





printf("\n\n");


r=n % 3;


if (r != 0) {





for (i=1;i%26lt;=r;i++)


{printf("%d",a[i]);


}


printf(",");


}





c=n/3;





for(k=1;k%26lt;=c;k++)


{printf("%d%d%d",a[r+1],a[r+2],a[r+3]);


r=r+3;


printf(",");


}





printf("\n\n");


system("pause");





}








The output is in the form for n=5


12,345,





how can we delete the last character in the output


using backspace character?
Reply:How many times.... DEV C++ IS NOT A LANGUAGE!!!


C++ is the language you are coding in. Dev C++ is just an editor - you might as well ask "what is the Notepad C++ program for...". To my knowledge this will be the third time I have informed you of this fundamental fact.


How do you empty an array in C++?

I need to empty an array under a certain condition. When I declare the array, I declare it as:





char str[81];





I fill it up by reading in characters from a file, and, when I move to the next line in the file, I want to empty out all of those characters to fill it up again, with new characters.





Will adding a '\0' after the last character in the second set of characters have the same effect as re-initializing the array? Is there a better way?

How do you empty an array in C++?
I agree with "Jay".


u wont need to empty it. it'll just get overwritted when u read new line from the file. Adding NULL after the last character...denotes that the string should be read upto NULL.


So every thing u get a line read in the str, add a NULL at the end.





if u want to empty a string u can do this ..





str[0] = NULL;


%26lt;or%26gt;


str[0] = '\0';
Reply:Adding a '\0' after the last character has been placed in the array is a good idea since 99.9% C and C++ functions expect character array strings to be null terminated (otherwise they would not be able to know where the end of the string is?). But that's not reinitializing the array. There is no "reinitializing" needed. once you're done with that line, just start again at index zero and read the next line like you read the last one. A character array as declared is nothing more than a small block of memory.
Reply:use ReDim
Reply:the previous answer:


str = 0;


is a really bad idea, and the compiler shouldn't let you do it...





To answer your question, most functions in C++ will accept an array of characters in which there are some number of characters followed by a null character and treat that as a string.





So, for instance,





#include %26lt;iostream%26gt;





int main() {





char str[81];





str[0] = 'a';


str[1] = 0;





std::cout %26lt;%26lt; str;





return 0;


}





will print out the letter 'a'.





Assuming you are passing your array of characters to something that works this way (looks for a series of characters followed by a null character), the scheme you've decribed (setting "the last character in the second set of characters" to 0) should work for you.
Reply:str = 0;
Reply:When you declare char str[81] what you are really doing is allocating a block of 81 contiguous (sequential) characters, then setting str to point to that block. So, it's generally a bad idea to later assign str to NULL or 0.





As others have mentioned, you don't really need to reinitialize, just reuse the same array and it'll overwrite. However, if you're using the "array" as a string you'll want to add a '\0' to the end after reading each line, so it'll print out and work with string functions fine.





If you really want to initialize the array to some value, the fastest way is with memset(): memset(str, 0, 81); This will fill the memory block with zeroes (the second argument).





BTW, if you're using C++ you probably want to learn about the STL (standard template library) and use either a vector%26lt;char%26gt; or string object. It's much simpler and safer than using C-style arrays. For example:





string str = "";


str += 'a'; // append character 'a' to the end of the string


printf("%s\n", str.c_str()); // output with printf()


cout %26lt;%26lt; str %26lt;%26lt; endl; // output with c++ style iostreams


str.clear(); // clear the string.
Reply:one thing I need to suggest u is that there is no need to empty an array.


just initialize to some value like 'NULL' (zero is ascii value of null). It helps to verify whether an element is empty or not(in this case null or not).


What is the dev c++ formula that declares an array of 20 integers. Accept a number to determine the.........?

what is the dev c++ formula that declares an array of 20 integers. Accept a number to determine the number of 0 or 1 inputs(binary digits). Display decimal value using the output format:





Enter size: 4


1


0


1


1


Equivalent: 11


1x8=8


0x4=0


1x2=2


1x1=1

What is the dev c++ formula that declares an array of 20 integers. Accept a number to determine the.........?
Hello Edrew !!





Here is your solution:








#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;math.h%26gt;





void main()


{


int num[20]={0};


int total,i;


double sum=0;


clrscr();


cout%26lt;%26lt;"How many digits do you wish to Enter : ";


cin%26gt;%26gt;total;





if(total%26gt;0 %26amp;%26amp; total%26lt;=20)


{


cout%26lt;%26lt;endl%26lt;%26lt;"Please Enter "%26lt;%26lt;total%26lt;%26lt;" digits : "%26lt;%26lt;endl;


for(i=0;i%26lt;total;i++)


{


cin%26gt;%26gt;num[i];


}








for(i=0;i%26lt;total;i++)


{


sum=sum + num[i]*pow(2,total-i-1);


cout%26lt;%26lt;endl%26lt;%26lt;num[i] %26lt;%26lt;"*"%26lt;%26lt;pow(2,total-i-1)%26lt;%26lt;"="%26lt;%26lt;num[i]*pow...


}


cout%26lt;%26lt;endl%26lt;%26lt;endl%26lt;%26lt;"Equivalent is : "%26lt;%26lt;sum;


}


else


cout%26lt;%26lt;"Please Enter value between 0 and 20..";





getch();


}
Reply:Try searching the net for C++ tutorials and resources
Reply:Try searching the net for C++ tutorials and resources. It's worth bearing in mind that Dev C++ is an editor, not a language - the languages it edits are C or C++.

floral centerpieces

Writing an array and visiting each element of the array in C programming?

Well i don't understand how arrays really work, and I dont understand how to grab the element of the array, can someone


explain and show how to do this

Writing an array and visiting each element of the array in C programming?
Array id a data structure, it is a memory like in which u can store the datas of same type[ like all integers or all characters]


in adjacent locations..


Suppose u want to store marks of 5 subjects, u have to declare an array name 'sub' and of size 5, and its positions are 0, 1, 2, 3 ,4. now if u want to access the ur 3rd subject marks , u have to call it by the array name %26amp; its position as sub[2].


For more details, try google search...


All the best.......


How to return a multidimensinal array in C++?

i have the following array as private member in 1 class:





bool array[100][100];





i need to use the filled up array in another class so i need a get method to return the array. but





bool[][] getArray();





and bool* getArray();





both does not work..





thanks!

How to return a multidimensinal array in C++?
try to use : return array[0][0];
Reply:You may use one of the following methods:


1. Return a bool** like -


bool** getArray() {


return array;


}


2. Take in a reference -


void getArray(bool **%26amp;arr) {


arr = array;


}


However, you would also need to know the 1st (row) and 2nd(column) size of the 2d array. Hence the following would be a better solution -


--


void getArray(bool **%26amp;arr, int %26amp;row, int %26amp;col) {


arr = array;


row = n_rows;


col = n_cols;


}


How do I transfer an array table to a function as a parameter in the syntax programming of C++?

I just solve informatic problems in c++. I have a string array of data which I want to make some comparing with a temp string array so it can move on. That's easy. I use loops and ifs. But the problem is that I use it many times and I want to organize my program. Therefore, i intend to pass the string array of data as a parameter in a particular function. In fact, I would really be appreciated if I can transfer a parameter data type of a string array by reference. Anyways a lot of help would be appreciated.

How do I transfer an array table to a function as a parameter in the syntax programming of C++?
char strArray[][6] = {"AAAAA", "BBBBB", "CCCCC", "DDDDD", "EEEEE"};





int stringCount = sizeof(strArray)/sizeof("AAAAA");





int TestStringArray(char A[][6], char B[])


{


for(int i = 0; i %26lt; stringCount; i++)


{


if(0 == strcmp(A[i], B))


{


return i;


}


}


return -1;








}








void main()


{


char B[] = "EEEEE";





int result = TestStringArray(strArray, B);


}