-1

I know other questions have been asked about this topic but I could not find one for exactly what I am looking for. I am taking a course on C and was presented with the following challenge: "Create a new application and create four character arrays to hold the following lines of text:

'Roses are Red. Violets Are Blue. C Programming is Fun. And Sometimes Makes my Head Hurt.' Make sure your character arrays are large enough to accommodate the character used to terminate C strings. Using a correctly formatted printf() command and signifier, output the string array values. "

Here is the code I have so far:

#include <stdio.h>

int main()
{

   char firstLine [] = "Roses are red.";
   char secondLine [] = "Violets are blue.";
   char thirdLine [] = "C programming is fun";
   char fourthLine [] = "And sometimes makes my head hurt";
}

Instead of manually counting the number of characters in each array and then putting that number in the "[]", is there a way to determine the length of character in each string?

toblerone_country
  • 577
  • 14
  • 26
  • Justin, following other comments below, get in the good habit of compiling your code with **warnings** enabled in your compile string. At a minimum, something like `gcc -Wall -Wextra -o outputfile inputfile.c` – David C. Rankin Sep 02 '14 at 03:42

2 Answers2

3

The syntax:

char str[] = "Some text.";

already counts the right length for the string . You don't have to take any further action. Leaving the [] empty (in this context) means that the array has the exact size required to store the string.

You can inspect this by doing printf("The size is %zu.\n", sizeof str); , note that this will be 1 more than the result of strlen because strings have a null terminator.

M.M
  • 138,810
  • 21
  • 208
  • 365
1

Based on my research by using strlen

Code:

#include <stdio.h>
#include <string.h>

int main()
{
   char str [] = "Roses are red.";
   size_t len;

   len = strlen(str);
   printf("Length of |%s| is |%zu|\n", str, len);
   return(0);
}

output:

Length of |Roses are red.| is |14|

Source: http://www.gnu.org/software/libc/manual/html_node/String-Length.html

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58