Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Just cannot understand pointers

Tags:

arrays

c

pointers

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?

like image 285
Robert Benedict Avatar asked May 31 '26 19:05

Robert Benedict


1 Answers

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.

like image 190
Chris K Avatar answered Jun 02 '26 08:06

Chris K