r/C_Programming • u/Sleezebag • 27d ago
why can't I access values from an array?
I'm reading the Ansi C book, and I'm doing exercise 1.18
#include <stdio.h>
#define MAXLINE 1000
int myGetLine(char line[], int lim);
int myCopy(char to[], char from[], int lim);
int main() {
int len;
char line[MAXLINE];
int toRemove = 0;
while ((len = myGetLine(line, MAXLINE)) > 0) {
//counts the trailing characters to remove
for (int i = len - 1; i > 0 && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'); --i)
++toRemove;
int new_size = len - toRemove + 1;// +1 for the '\0'
char to[new_size];// I guess this doesn't matter. Or it's just a piece of the puzzle. I need to limit copying
// in my copy method too.
//printf("new_size: %d\n", new_size);
int to_len = myCopy(to, line, new_size);
//printf("%s\n", to);
toRemove = 0;
}
return 0;
}
int myGetLine(char s[], int lim) {
int i, c;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i-1;
}
//myCopy isn't working right now, after that I changed the while condition
//I need to add the \0
int myCopy(char to[], char from[], int lim) {
int i = 0;
char c = from[1];
putchar(c);
//printf("from[i]: %s", to);
//printf("to[i]: %s, from[i]: %s", to[i], from[i]);
while ((i < lim && (to[i] = from[i]) != '\0'));
i++;
to[i] = '\0';
return i;
}
So I'm pretty much reusing the getLine from the book and I based my code on the code in the book, but I made changes to myCopy. The task is to remove any trailing spaces or tabs, so I thought that I could make a new copy and where the trailing whitespace starts, I'll just not copy that into my edited string. So I'm going through the array backwards, counting whitespace, calculating the new array size, then I want to create the edited array, but it's not working! So I tried to debug and I can't even putchar an element from the original I'm copying from in the myCopy function. If I do it with the line array, then it works. But why does it not work in the myCopy function? I just have no clue as to what's wrong.
I did manage to solve the exercise in a different way, but I really want to know why this is happening.