Search code examples
stringc-stringsstring-literals

How can I write a certain number of characters per line out of a string literal?


I am learning C and trying to figure out strings. How do I break down a simple string literal to print out 6 chars per line? I'm kinda confused if my approach is on track. Thanks!

For example:

   char someString = "Hello world, I like to fly high like a cloud!";
   char * temp = malloc(30);

   temp = someString;          //so I can manipulate a string literal

   int count = 6;

   for(int i=0; i<30; i++)
   {
      if(i<count)
      {      
         printf("%c", temp[i]);        
      }
      if(i == count)
      {
         printf("\n");
         count = count + count;
      }
    }

    free(temp);    //prevent memory leak










   

Solution

  • In C, a string is actually an array of characters, so it must be declared as an array... which just means you need to insert [] after SomeString in your first line. And since you are not modifying the string, there is no need to make a copy... but if you do, you cannot copy a string (which, again, is an array) with a simple assignment. You would have to use the strcpy function, or better yet, strdup, which also handles the memory allocation for you.

    Your logic in the for loop is almost correct, except that you are doubling count on each iteration... which is fine for the first two iterations, in which count is 6 and 12, but then on the third iteration it's 24. Instead of count = count + count;, you want count += 6; If you like, you can define the character block size as a macro, so it can be easily changed: put the line #define STEP 6 near the top of your program. Then change int count = 6; to int count = STEP;, and count += 6; to count += STEP;