1

I'm trying to pass a char[] to a function however every time that I try to it loses it's value. I can pass it to other functions, but when I pass it to one specific one it just loses the string stored in the array. code follows:

int test(char one[], int len) {
    printf("The string: %s, The size: %d", one, len);
    int to = rd_field_length(one, 0, len);
    return to;
}
int main(){
    rd_open("thefile");
    char line[200] = "";
    double d;
    int * err;
    int c, length = 0;
    if(fp != NULL) {
            while((c = rd_getchar()) != EOF && c != '\n'){
                     line[length] = c;
                     length++;
            }
    }
    int to = test(line, length);
}
int rd_field_length(char buf[], int cur, int end ){
    printf("BUF: %s", buf);
    return 0;
}

Line gets passed to test and I can access the string, however when passing to rd_field_length it loses it's value.

3
  • One thing that jumps out is you seem to be passing an unterminated character array to printf() as if it were a null-terminated string. Another is that you seem to be doing no checking to make sure you don't fill the array beyond its allocated length. Depending on implementation details, that could get very interesting if the array writes overflow into the storage of the index variable "length" which you are using to do the writing! Commented Feb 13, 2014 at 22:20
  • Yeah even when setting the last value of line to \0 at the end of the while loop doesn't seem to work. Commented Feb 13, 2014 at 22:35
  • Maybe char line[200] = {0}; to initialize the entire array to 0. Or add one[len] = 0 at the beginning of test() Commented Feb 13, 2014 at 23:30

1 Answer 1

1

As you don't have a prototype in scope and the function is called before it is defined, variables will be passed as integers. If you have 32 bit integers and 64 bit pointers, the loss of precision will likely result in a null or invalid pointer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.