Hello there, I'm new here and I need some help:
I am asked to write a function that recieves a pointer to string, a zero-based integers, "start" and "end", and int "dist".
In this function I need to modify the string by moving the substring starting from "start" to "end" by "dist" characters. for example: the string "ronald mashu" if I call the function move(s, 0, 3, 2) when s is the pointer to "ronald mashu", if I print s after the function call I should recieve "ldrona mashu".
The problem is that inside the function I manage to get the correct output in a local pointer but I can't seem to get the original pointer point to it.
Here's the code:
Code:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <string.h>
5
6 int move_chars (char *str, int start, int end, int dist) {
7 int index, subindex = 0;
8 char *sub = malloc ((end - start + 1) * sizeof(char));
9 char *old = malloc ((start + 1) * sizeof(char));
10 char *subStart = sub;
11 char *oldStart = old;
12 /* Validity Checks */
13 if (start < 0 || end < 0 || dist < 0) {
14 printf("Invalid Arguments");
15 return 1;
16 }
17 for (index = 0 ; index < start ; index++) {
18 old[0] = str[0];
19 str++;
20 old++;
21 } 22 for (index = start ; index <= end ; index++) {
23 sub[0] = str[0];
24 subindex++;
25 str++;
26 sub++;
27 }
28 for (index = 0 ; index < dist ; index++) {
29 old[0] = str[0];
30 str++;
31 old++;
32 }
33 sub = subStart;
34 old = oldStart;
35 strcat(old, sub);
36 strcat(old, str);
37 str = old;
38 free(old);
39 free(sub);
40 return 0;
41 }
42
43 int main() {
44 char *s = "ronald mashu";
45 move_chars(s, 0, 3, 2);
46 printf("%s\n", s);
47 return 0;
48 }
Ideas?
Thanks in advance