Originally Posted by
RyanC
if I have two int arrays with size 10 (assumable), lets say that's the name of first one is arr1 , the other one is arr2 . my question is when I write arr1=arr2, logically it means that copy the DATA of arr2 to the memory location of arr1, meaning with this, smashing all the data of arr1 and replacing it by the data of arr2. is that right?
No, it is absolutely wrong.
Also, stop saying "smashing all the data"; that was from GReaper's bad analogy, right? The analogy just doesn't work: in C, if your variable is like a table that holds a value that is the cake, when you want to replace the cake, the cake is just magically cleanly replaced, with the previous cake disappearing into thin air. No smashing is involved. Obviously that doesn't make sense in real life, hence the analogy simply fails to convey the point.
If you really want an analogy, use the analogy of an analogue clock, except that it has a single hand (i.e., the hour hand), and instead of 12 hours, it is numbered from say, 0 to 255 (the typical range of values for an unsigned char). When you start with the value of 5 and assign 10, what happens is that the hour hand starts pointing at 5, then upon the assignment, it very quickly changes to point at 10. You will find this analogy useful to understand modulo arithmetic, and indeed another name for that is "clock arithmetic".
Originally Posted by
RyanC
btw I know in standard types variables like integers, if I have int x ; int y; and write x=y , what actually happen copying the data of y to x. but I guess might be differently in arrays!
Why guess? Write a program and find out why your assumptions do not hold:
Code:
#include <stdio.h>
void print_array(int arr[], size_t size)
{
size_t i;
for (i = 0; i < size; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main(void)
{
int arr1[10] = {0};
int arr2[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_array(arr1, sizeof(arr1) / sizeof(arr1[0]));
arr1 = arr2;
print_array(arr1, sizeof(arr1) / sizeof(arr1[0]));
return 0;
}
If you are right, the program will compile, and then you will see that before the assignment, arr1 consists of all 0s, and after the assignment, arr1 consists of the same values in the same order as arr2. Easy!
EDIT:
Originally Posted by
RyanC
Moreover, is it different(in aspect of memory and addressing) to write const int x=5; int y=x ; from const int x=5; int y=5 ((assuming the value of x is constant 5)) in an aspect of references ? because for instance in Jave if we write String x="Awesome"; String y=x ; it's referencing to the same value , but String x="Awesome"; String y="Awesome" , is totally not referencing to the same value .
C does not have Java-style reference objects. C does have a reference mechanism, but explicitly in the form of pointers. Java-style reference objects are like implicit C pointers without pointer syntax (and hence without pointer arithmetic).