Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C programming language, complete the following: C++ has a nice vector class t

ID: 3872681 • Letter: I

Question

In C programming language, complete the following:

C++ has a nice vector class that automatically
adjusts an array size as needed. C does not have
any such feature (until now :) ).

Write a program that prompts the user for characters
(not strings!). As the user enters characters ONE AT
A TIME (I suggest using getchar() ), your
program must call your "vector function" (that you
must write) to automatically adjust the character
array size to hold the input.

The vector function must use malloc/calloc to
create/adjust the array size. You cannot not use realloc!

You may also want to read the man page on memcpy.

The vector function must return a pointer (to the array)
to the main routine (you will probably want to pass
in the array also). This means your vector function must
be of type "char *"

You can adjust the array in chunks of 5 or 10 characters
(vs 1 character) if you want.

When the user enters "return" (in place of a character)
your program must append the '' character to the end
(making it a string). Your program must then append
the new string to the text/string "HW 4 input: "
(be carefull here). Your program must then print out
the resulting string.

getchar();


SAMPLE RUN:
-----------
Enter characters: 1234567

HW 4 input: 1234567

Explanation / Answer

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

char* vector(char arr[], int size, int step) {
char *dest;
dest = (char*)malloc ((size+step) * sizeof (char));
memcpy( dest, arr, size-1 );
return dest;
}

int main()
{
char c;
char *str;
int len = 10;
str = (char*)malloc (len * sizeof (char));
int size = 0;
printf("Enter characters: ");
do
{
c = getchar();
if (c == ' ') break;
str[size++] = c;
if (size == len -1) {
str = vector(str, len, 10);
len += 10;
}
} while (c != ' ' && c != EOF);
str[size] = '';

char result[] = "HW 4 input: ";
strcat(result, str);
printf("%s ", result);
return 0;
}