I'm doing a problem from Programming in C that requires me to make a program that takes a word, and a start position as well as number of words to take, and puts it into a result array. I've seen some solutions online, but they all use POINTERS, which I can't use, because we're not in that section yet.
#include <stdio.h>
char substring (char source[], int start, int count, char result[])
{
int i;
for (i = 0; (i < count) && (source[start + i] != '\0'); ++i)
{
result[i] = source[start + i];
}
result[i + 1] = '\0';
return result;
}
int main (void)
{
char substring (char source[], int start, int count, char result[]);
char source[81];
char result[81];
int start, count;
printf ("Enter the word you want to check!\n");
printf ("And the start position as well as the number of words to count!\n");
scanf ("%s %i %i", &source[81], &start, &count);
printf ("Your result is: %s\n", substring(source, start, count, result));
}
I keep on getting errors when compiling and when I fix them I don't get a result. Thanks.
&source[81]is a major problem; you're passing beyond the end of your arraychar source[81];toscanf(). You need either&source[0]or justsourcethere instead.char source[]the compiler treats it aschar *source. So in thesubstringfunction you don't have arrays, you have pointers.main()for function:substring()2) when calling any of thescanf()family of functions, always check the returned value (not the parameter values) to assure the operation was successful. 3) when callingscanf()and using the%sformat specifier, always include a 'max characters' modifier that is one less than the length of the input buffer, to avoid any buffer overflow. Note: a buffer overflow is undefined behavior and can lead to a seg fault event.