melkadri melkadri - 1 month ago 6
C Question

Programming in C: Making a substring function

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.

Answer

Change

scanf ("%s %i %i", &source[81], &start, &count)

to

scanf ("%s %i %i", source, &start, &count)

Also in the function you are returning a char and trying to print it with a %s. You should return a char* for that. So, the function becomes,

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;
}
Comments