I tried the following code:  int a[4] = {0}; int b[4] = {5}; int c[4]; printf("%d %d %d %d %d %d\n", a[0], a[3] , b[0], b[3], c[0], c[3]);   And got the following result:  0 0 5 0 random random   While I get why I got random values for the c array, I don't understand why the assignation {5} does not work as {0} and only initialize the first element of the array.  Is there a way to initialize array b elements to the same value different from 0? (without using a memset, or a for loop)
5742
I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.  I could swear I once knew a simple way to do this. I could use memset() in my case, but isn't there a way to do this that is built right into the C syntax?
16473
Consider the class below that represents a Broker:  public class Broker {     public string Name = string.Empty;     public int Weight = 0;      public Broker(string n, int w)     {         this.Name = n;         this.Weight = w;     } }   I'd like to randomly select a Broker from an array, taking into account their weights.  What do you think of the code below?  class Program     {         private static Random _rnd = new Random();          public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight)         {             // totalWeight is the sum of all brokers' weight              int randomNumber = _rnd.Next(0, totalWeight);              Broker selectedBroker = null;             foreach (Broker broker in brokers)             {                 if (randomNumber &lt;= broker.Weight)                 {                     selectedBroker = broker;                     break;                 }                  randomNumber = randomNumber - broker.Weight;             }              return selectedBroker;         }           static void Main(string[] args)         {             List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();             brokers.Add(new Broker("A", 10));             brokers.Add(new Broker("B", 20));             brokers.Add(new Broker("C", 20));             brokers.Add(new Broker("D", 10));              // total the weigth             int totalWeight = 0;             foreach (Broker broker in brokers)             {                 totalWeight += broker.Weight;             }              while (true)             {                 Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;();                  Broker selectedBroker = null;                  for (int i = 0; i &lt; 1000; i++)                 {                     selectedBroker = GetBroker(brokers, totalWeight);                     if (selectedBroker != null)                     {                         if (result.ContainsKey(selectedBroker.Name))                         {                             result[selectedBroker.Name] = result[selectedBroker.Name] + 1;                         }                         else                         {                             result.Add(selectedBroker.Name, 1);                         }                     }                 }                   Console.WriteLine("A\t\t" + result["A"]);                 Console.WriteLine("B\t\t" + result["B"]);                 Console.WriteLine("C\t\t" + result["C"]);                 Console.WriteLine("D\t\t" + result["D"]);                  result.Clear();                 Console.WriteLine();                 Console.ReadLine();             }         }     }   I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.  Is there a more accurate algorithm?  Thanks!
116782
Possible Duplicate:          see this code    #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))     int array[] = {23,34,12,17,204,99,16};     int main()     {         int d;         for(d=-1;d &lt;= TOTAL_ELEMENTS-2;d++)            printf("%d\n",array[d+1]);         return 0;    }    now this loop won't run. sizeof() would return an unsigned value so TOTAL_ELEMENTS has an unsigned value. now , coming to the for loop, please tell me if the unary operator '-' works on signed int 2 or an implicit conversion takes place into unsigned and then the '-' operator works.
13470
I am a little surprised by the following.  Example 1:  char s[100] = "abcd"; // declare and initialize - WORKS   Example 2:  char s[100]; // declare s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)   I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
84760
I am surprised that I can't initialize my fields in structs, why is it like that? Like:  struct MyStruct {     private int a = 90; }   but it's a complie time error. I don't know why it's a problem? Please explain this to me.
4701
How do I generate a random int value in a specific range? I have tried the following, but those do not work: Attempt 1: randomNum = minimum + (int)(Math.random() * maximum);  Bug: randomNum can be bigger than maximum. Attempt 2: Random rn = new Random(); int n = maximum - minimum + 1; int i = rn.nextInt() % n; randomNum =  minimum + i;  Bug: randomNum can be smaller than minimum.
43627
Let $x = x(1), \dots , x(n)$ be a bit string containing exactly $m$ occurrences of 1. Consider the following operation on $x$: we choose a random pair of indices $(i,j),$ and we swap $x(i)$ and $x(j)$ so that $x'(i) = x(j),$ $x'(j) = x(i),$ while $x'(k) = x(k)$ if $k \neq i$ and $k \neq j.$ (If $i = j,$ therefore, then we change nothing.) Let $X_1 = x,$ and let $X_2, \dots, X_N$ be obtained by such a sequence of operations (always swapping a new random pair) that so $X_{r+1} = X_r$. The number of 1s remains $m$ in each iteration. Show for each $i$, we have $P(X_N (i) = 1) \rightarrow \frac{m}{n}$ as $N \rightarrow \infty$.   What's confusing me is that it seems as though the probability on any iteration of $X_j$ that $X_j(i) = 1$ is always $\frac{m}{n}$, which would make the problem trivial.
86209
I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?  For example:      typedef struct     {         char *str;     } words;      main()     {         words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in.     }   Is this possible?    I've researched this: words* array = (words*)malloc(sizeof(words) * 100);  I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as:      words* array = (words*)malloc(sizeof(words));   However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment.    I've made a little progress however:      typedef struct {         char *str;     } words;      // Allocate first string.     words x = (words) malloc(sizeof(words));     x[0].str = "john";      // Allocate second string.     x=(words*) realloc(x, sizeof(words));     x[1].FirstName = "bob";      // printf second string.     printf("%s", x[1].str); --&gt; This is working, it's printing out bob.      free(x); // Free up memory.      printf("%s", x[1].str); --&gt; Not working since its still printing out BOB even though I freed up memory. What is wrong?   I did some error checking and this is what I found. If after I free up memory for x I add the following:      x=NULL;   then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least on my compiler? I'm using DevC??    Thanks, I understand now due to:     FirstName is a pointer to an array of char which is not being allocated by the malloc, only the pointer is being allocated and after you call free, it doesn't erase the memory, it just marks it as available on the heap to be over written later. – MattSmith   Update  I'm trying to modularize and put the creation of my array of structs in a function but nothing seems to work. I'm trying something very simple and I don't know what else to do. It's along the same lines as before, just another function, loaddata that is loading the data and outside the method I need to do some printing. How can I make it work? My code is as follows:      # include &lt;stdio.h&gt;     # include &lt;stdlib.h&gt;     # include &lt;string.h&gt;     # include &lt;ctype.h&gt;      typedef struct     {         char *str1;         char *str2;     } words;      void LoadData(words *, int *);      main()     {         words *x;         int num;          LoadData(&amp;x, &amp;num);          printf("%s %s", x[0].str1, x[0].str2);         printf("%s %s", x[1].str1, x[1].str2);          getch();     }//      void LoadData(words *x, int * num)     {         x = (words*) malloc(sizeof(words));          x[0].str1 = "johnnie\0";         x[0].str2 = "krapson\0";          x = (words*) realloc(x, sizeof(words)*2);         x[1].str1 = "bob\0";         x[1].str2 = "marley\0";          *num=*num+1;     }//   This simple test code is crashing and I have no idea why. Where is the bug?
73942
Can someone explain to me how XOR swapping of two variables with no temp variable works?  void xorSwap (int *x, int *y) {     if (x != y) {         *x ^= *y;         *y ^= *x;         *x ^= *y;     } }   I understand WHAT it does, but can someone walk me through the logic of how it works?
9601
I want to take a floating point number in C++, like 2.25125, and a int array filled with the binary value that is used to store the float in memory (IEEE 754).  So I could take a number, and end up with a int num[16] array with the binary value of the float: num[0] would be 1 num[1] would be 1 num[2] would be 0 num[3] would be 1 and so on...  Putting an int into an array isn't difficult, just the process of getting the binary value of a float is where I'm stuck. Can you just read the binary in the memory that the float variable? If not, how could I go about doing this in C++?  EDIT: The reason for doing the comparison this way is that I am wanting to learn to do bitwise operations in C++.
90115
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it? What I have now is:   Student * db = new Student[5];   But each element in that array is the student object, not a pointer to the student object. Thanks.
5148
I have recently been thinking about the difference between the two ways of defining an array:   int[] array int array[]   Is there a difference?
981
How do I determine the size of my array in C?   That is, the number of elements the array can hold?
26165
I have a class that contains a dynamically allocated array, say  class A {     int* myArray;     A()     {         myArray = 0;     }     A(int size)     {         myArray = new int[size];     }     ~A()     {         // Note that as per MikeB's helpful style critique, no need to check against 0.         delete [] myArray;     } }   But now I want to create a dynamically allocated array of these classes. Here's my current code:  A* arrayOfAs = new A[5]; for (int i = 0; i &lt; 5; ++i) {     arrayOfAs[i] = A(3); }   But this blows up terribly. Because the new A object created (with the A(3) call) gets destructed when the for loop iteration finishes, and this means that the internal myArray of that A instance gets delete []-ed.  So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:   Creating a copy constructor for A. Using vector&lt;int&gt; and vector&lt;A&gt; so I don't have to worry about all this. Instead of having arrayOfAs be an array of A objects, have it be an array of A* pointers.   I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.  (Also, style critiques appreciated, since it's been a while since I did C++.)  Update for future viewers: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why vectors are a good way to go.
33748
What is the difference between int *a[3] and int (*a)[3]?
67149
I'm trying to create an array of arrays that will be using repeated data, something like below:  int[] list1 = new int[4] { 1, 2, 3, 4 }; int[] list2 = new int[4] { 5, 6, 7, 8 }; int[] list3 = new int[4] { 1, 3, 2, 1 }; int[] list4 = new int[4] { 5, 4, 3, 2 };  int[,] lists = new int[4, 4] {  list1 ,  list2 ,  list3 ,  list4  };   I can't get it to work and so I'm wondering if I'm approaching this wrong.   What I'm attempting to do is create some sort of method to create a long list of the values so I can process them in a specific order, repeatedly. Something like,  int[,] lists = new int[90,4] { list1, list1, list3, list1, list2, (and so on)};  for (int i = 0; i &lt; 90; ++i) {    doStuff(lists[i]); }   and have the arrays passed to doStuff() in order. Am I going about this entirely wrong, or am I missing something for creating the array of arrays?
24071
I'm trying to understand Python's approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within main(), but not the value of n?  def f(n, x):     n = 2     x.append(4)     print('In f():', n, x)  def main():     n = 1     x = [0,1,2,3]     print('Before:', n, x)     f(n, x)     print('After: ', n, x)  main()   Output:  Before: 1 [0, 1, 2, 3] In f(): 2 [0, 1, 2, 3, 4] After:  1 [0, 1, 2, 3, 4]