array values in for loop

This is a discussion on array values in for loop within the C Programming forums, part of the General Programming Boards category; Code: int primeGen(a1){ int b1; int b2; b2=0; int b4; int *b5; int b6; b5 = (int *)calloc(a1*2,sizeof(int)); b5[0]=1; b5[1]=2; ...

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    1

    array values in for loop

    Code:
    int primeGen(a1){
      int b1;
      int b2;
      b2=0;
      int b4;
      int *b5;
      int b6;
      b5 = (int *)calloc(a1*2,sizeof(int));
      b5[0]=1;
      b5[1]=2;
      b5[3]=2;
      b5[4]=3;
      for(b1=5; b2 < a1; b1++){
        if (checkPrime(b1)) {
            /* What I'm doing is ordering the array b5
            such that entry i*2 is the ith index,
            and that i*2+1 is the ith prime */
          b5[5+b2*2]=3+b2; //These seem to be working fine
          b5[6+b2*2]=b1; 
          b2++;
        }
      }
      for(b6=0;b6<a1;b6++){
        printf("%d %d \n",b5[b6],b5[b6+1]); //But down here the data's all messed up
      }
      return 0;
    }
    I'm not sure what's going wrong. The data is correct when it's assigned, but after the for loop I try and get the values from the array and they seem totally random. What's going on?
    Thanks

  2. #2
    qny
    qny is offline
    Registered User
    Join Date
    Sep 2012
    Posts
    355
    Code:
      for(b6=0;b6<a1;b6++){
        printf("%d %d \n",b5[b6],b5[b6+1]); //But down here the data's all messed up
      }
    You are printing the elements twice. For example element at index 3. you print it in second position when b6 is 2; and on the next line, when b6 is 3, you print it again in first position.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 02-23-2012, 05:26 PM
  2. Adding values to array in a for loop
    By bman900 in forum C Programming
    Replies: 1
    Last Post: 11-06-2010, 07:58 AM
  3. Converting Char Array Loop values to integer
    By azamsharp1 in forum C Programming
    Replies: 8
    Last Post: 10-27-2005, 10:13 AM
  4. for loop again and array values, need help
    By InvariantLoop in forum C Programming
    Replies: 7
    Last Post: 01-28-2005, 10:29 PM
  5. printing values loop.
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 07-02-2002, 03:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21