Here's the updated code with your suggestions.
Code:
//
// main.c
// String Parsing
//
// Created by Joshua Ernzen on 10/22/17.
// Copyright © 2017 Joshua Ernzen. All rights reserved.
//
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define BUFFER 1024
void PressEnter(void);
int main()
{
char CharacterInput[BUFFER], ConvertedToString[BUFFER];
uint16_t ProgramCounter, StringLength;
printf("Enter a string:\n");
fgets(CharacterInput, sizeof(CharacterInput), stdin);
printf("Printing directly from \"CharacterInput\":\n");
printf("%s", CharacterInput);
PressEnter();
StringLength = strlen(CharacterInput);
printf("Printing from for loop:\n");
for(ProgramCounter = 0; ProgramCounter < StringLength; ProgramCounter++)
{
printf("%c\n", CharacterInput[ProgramCounter]);
if(CharacterInput[ProgramCounter] == '\n' || CharacterInput[ProgramCounter] == '\0')
break;
}
PressEnter();
printf("\"CharacterInput\" is %lu bytes long\n", strlen(CharacterInput));
printf("There are %d characters\n", ProgramCounter);
printf("Remember, \"CharacterInput\" should be one byte longer than the number of characters due to the NULL terminator\n");
PressEnter();
printf("This is now copying \"CharacterInput\" to \"*ConvertedToString\"\n");
strncpy(ConvertedToString, CharacterInput, sizeof(ConvertedToString));
printf("%s", ConvertedToString);
PressEnter();
printf("Clearing \"CharacterInput\". Let's see if we saved the original content to \"ConvertedToString\":\n");
memset(CharacterInput, 0x00, sizeof(CharacterInput));
printf("Contents of \"CharacterInput\":\n");
printf("%s\n", CharacterInput);
printf("Contents of \"*ConvertedString\":\n");
printf("%s\n", ConvertedToString);
PressEnter();
return 0;
}
void PressEnter()
{
int8_t EnterBuffer;
printf("Press enter to continue: ");
do
EnterBuffer = getchar();
while(EnterBuffer != '\n' && EnterBuffer != EOF);
return;
}
I was also thinking about removing "ConvertedToString[BUFFER]" to malloc. I've never played with malloc before so I would think this would be a good attempt for it.