0

I am newbie in C. I do not know why I am getting this error and how to fix it?

void FPS_PRINT_ENROLLED(){
  int checkNum = 0;
  int ID = 0;
  int num_Enroll = 0;
  num_Enroll = Available_ID();
  char strNum[3] = 0;
  itoa(num_Enroll, strNum);
  uint32_t numLen = strlen((char *)strNum);
  UART_send_A3("Number of Stored Prints: ", 25);
  UART_send_A3(&strNum, numLen);
  }

The error message is: array initializer must be an initializer list or string literal

Please see the attached screenshot of the error message. Also, the c file is attached.

Screenshot of error message

By the way, this is in PSoC Creator 4.1 which uses C language.

code file download link through GoogleDrive

kenlukas
  • 3,616
  • 9
  • 25
  • 36
  • 1
    this line: `char strNum[3] = 0;` is a problem. The variable on the left is an array of chars with three elements. The initializer on the right is a a scalar int. They types do not match. Try putting the initializer in curly braces which will assign 0 to each element, like this: `char strNum[3] = {0};` – bruceg Nov 14 '18 at 03:21
  • 1
    @bruceg Such a nice explanation. This should go in as an answer. – Sandy Nov 14 '18 at 03:32
  • 1
    Great @bruceg , thanks! – Sulaiman Alsuhaimi Nov 14 '18 at 05:35

1 Answers1

0
char strNum[3] = 0;

This line creates a three character string. You then use it as a string with the function strlen and the uart_send.

As a C string it must be terminated with a null character, so you only have two usable characters. It must also be initialised as a string, the compiler is telling you that you haven't done this correctly.

Try something like one of these lines

char strNum[3] = ""; // Empty string
char strNum[3] = "AB"; // Full string
char strNum[3] = "0"; // String holding the character zero
lod
  • 1,098
  • 10
  • 13
  • 1
    Detail: Although all 3 array elements are initialized to zero, the _string_ is only 1 character: `strNum[0]`. – chux - Reinstate Monica Nov 14 '18 at 03:43
  • Awesome! I changed it to char strNum[3] = "0"; and got it working. Will this affect my code if I keep it like this or you are just explaining to me? – Sulaiman Alsuhaimi Nov 14 '18 at 05:30
  • No, it is a perfectly valid piece of code. Keep in mind that it is a string representation of a number, not a number. You can't increment it or modify it like you would a number. If you have issues with that it would be best to ask another question. – lod Nov 14 '18 at 05:43
  • If your statement “It must also be initialised as a string” is meant to say that an array of `char` must be initialized with a string literal, then it is incorrect. As the compiler message notes, it may be initialized with an initializer list (enclosed in braces), such as `{ 2, 1, 0 }` or `{ 'a', 'b', 0 }`. – Eric Postpischil Nov 14 '18 at 11:59
  • `char strNum[3] = 0;` doesn't create jack, it is not valid C. Hence the compiler error. – Lundin Nov 14 '18 at 12:20