I'm having a really frustrating time trying to understand pointers, literally 90% of the errors I get when coding revolve entirely around pointers
So I have a char* array, mallocced and holding characters
strcpy only takes pointers for some reason, so if I want to strcpy array[x] to a destination, I can't just use
strcpy(destination,array[x])
because that gives me an error saying array[x] is a char, not a char*
now here's the thing I don't get - how do I make a pointer to array[x]? I don't understand pointers at all
When I use
char i;
char *j;
i = array[0];
j = &i;
strcpy(destination,j);
It gives me the letter, but with accompanying junk chars despite the fact I memsetted j before assigning it to &i
When I use
char *j;
j = &array[0];
strcpy(destination,j);
It adds the entire array
What's the difference? I'm assigning J to the address of x[0] in both cases aren't I?
You have lost track of where the variables are and what you are copying. Here is your code annotated with what it is doing.
char i; // reserves a variable of size char on the stack
char *j; // reserves a variable of size ptr on the stack
i = array[0]; // copies the first char from the array
// into variable i
j = &i; // copies the stack address of variable i into j..
// note that this is not the array as we
// previously copied the char out of the array
strcpy(destination,j); // you have not supplied destination, so
// no comment there but j is a pointer
// onto the stack AND NOT a pointer
// into the array.. thus who knows
// what characters it will copy afterwards
where as version 2 is different:
char *j; // reserves a variable on the stack of size ptr
j = &array[0]; // sets the contents of variable j to the address
// of the first element of the array.. note
// that this is the same as `j = array`
strcpy(destination,j); // starts copying the chars from j into
// destination, incrementing the pointer j
// one at a time until a null is found and
// the copying will stop
So in conclusion, version 2 is copying the array.. where as version 1 is copying data from the stack after copying the first character of the array onto the stack. Thus the behaviour is different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With