title: Chop up string into chunks of 512 bytes in c
body: <p>Im trying to write a function that takes a string and chops it up into chunks of 512 bytes. It takes the first 512 bytes in the string, and stores it in chopped[0] and then the next 512 in chopped[1]...etc. It seems to be working when I print out chopped in the function, but when I return chopped[0] is giving me the whole string and not just the first 512. Any ideas whats going on here?</p>
  
  <pre><code>char** chopString(){
      char string[]="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200";
  
      int len=strlen(string)+1;
      int i,j,bytes,blocks;
      int blockSize=512;
      bytes=len*sizeof(char);
      blocks=(int)ceil((double)bytes/blockSize);  //determine number of blocks rounded up
  
      char* chunk=malloc(blockSize+1);
      char* newChunk=malloc(blockSize+1);
      char** chopped=malloc(sizeof(char*)*(blocks+1));  //blockSize+1 for  null character
  
  
      for(j=0; j&lt;blocks; j++){
          len=strlen(string)+1;              //get length of string
          if(len&lt;blockSize){                    //if the string can fit in one block
              bytes=len;                        //the number of bytes to write is the length
          }else{                                //if it doesn't fit in one block
              bytes=blockSize;                  //then bytes to write is one block
          }
          strcpy(chunk,string);        //copy newString into chunk
          newChunk=chunk;                 //keep pointer to begining of chunk
  
          for(i=0; i&lt;bytes; i++){
              chunk++;
          }
          strcpy(string,chunk);        //set new string to remaining portion            
          *chunk='\0';                    //set end of chunk to null
          chopped[j]=newChunk;            //put chunk into array
          printf("Chopped[%d]: %s\n",j,chopped[j]);
          printf("length: %d",(int)strlen(chopped[j]));
      }
      chopped[j]=NULL;
      printf("\n"); 
      return chopped;
  }
  </code></pre>