C array declaration and assignment?

I've asked a similar question on structs here but I'm trying to figure out how C handles things like assigning variables and why it isn't allowed to assign them to eachother if they are functionally the same.

Lets say I have two arrays:

int x[10]; int y[10];

Why won't x = y compile? If they are both the same "signature" like that, then shouldn't you be able to assign them back and forth?

Can I declare these in a way that would allow me to do that in C? It makes sense to me that you would be able to, but maybe there is a way that this can be done? Typedefs for structs seemed to be the solution, would it be the same for array declaration and assignment?

I appreciate your guys help, I'm new to Stackoverflow but it has been a really good resource for me so far!

--------------Solutions-------------

The name of an array is actually the address of the first element of that array.

The example code you provide here is attempting to assign to something which is not an l-value.

It's like doing this;

int
x[10],
y[10];

&x[0] = &y[0];

You can do with structs what you're getting at here;

struct data
a,
b;

a = b;

And in fact if struct data is declared as;

struct data
{
int
x[10];
};

then you'd be doing exactly what you're trying to do here!

But you can't do it directly with arrays. Use memcpy().

When you declare those arrays, the compiler reserves space for 10 ints. When you assign one "array" (which is just a pointer to the first element), you'd just copy the pointers, not the contents.
For copying, there are functions like memcpy, if you want to assign x (or y) to something, you'd have to assign it to a int*.

int x [sz];
int *y = x;

This compiles and y will be the same as x.

In order to assign arrays you will have to assign the values inside the array.

ie. x=y is equivalent to

for(int i = 0; i < 10 < ++i)
{
x[i] = y[i];
}

You have to look at what the variables represent. In your code, you now have two chunks of memory, both big enough to hold 10 integers.

Now, x[0] is the first chunks 0th integer, and y[0] is the seconds. But x itself is a pointer to the first element. Likewise, y is a pointer to the second chunk.

So saying x = y would try to assign x to now be pointing at y's chunk. And x's array is a lost forever. If you dynamically allocated these 2 chunks with malloc, you would be able to say "x = y", setting x to point to the second dynamically allocated chunk, but losing x's chunk forever (memory leak).

This error is the compiler preventing you from doing so. To copy each element, you have to loop through the arrays:

for (int i = 0; i < 10; ++i)
{
x[i] = y[i];
}

In an attempt to complement Blank's answer, I devised the following program:

localhost:~ david$ cat test.c
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char * argv [])
{
struct data {
int c [2];
} x, y;
x.c[0] = x.c[1] = 0;
y.c[0] = y.c[1] = 1;
printf("x.c %p %i %i\n", x.c, x.c[0], x.c[1]);
printf("y.c %p %i %i\n", y.c, y.c[0], y.c[1]);
x = y;
printf("x.c %p %i %i\n", x.c, x.c[0], x.c[1]);
printf("y.c %p %i %i\n", y.c, y.c[0], y.c[1]);

return 0;
}

When executed, the following is output:

x.c 0x7fff5fbff870 0 0
y.c 0x7fff5fbff860 1 1
x.c 0x7fff5fbff870 1 1
y.c 0x7fff5fbff860 1 1

The point is to illustrate how the copy of structures' values occurs.

Some messages here say that the name of an array yields the address of its first element. It's not always true:

#include <stdio.h>

int
main(void)
{
int array[10];

/*
* Print the size of the whole array then the size of a pointer to the
* first element.
*/
printf("%u %u\n", (unsigned int)sizeof array, (unsigned int)sizeof &array[0]);

/*
* You can take the address of array, which gives you a pointer to the whole
* array. The difference between ``pointer to array'' and ``pointer to the
* first element of the array'' matters when you're doing pointer arithmetic.
*/
printf("%p %p\n", (void*)(&array + 1), (void*)(array + 1));

return 0;
}

Output:

40 4
0xbfbf2ca4 0xbfbf2c80

When saying "int x[10]" is saying, "reserve some room for 10 integers and pass me a pointer to the location". So for the copy to make sense you'd need to operate on the memory pointed by, rather than 'the name of the memory location'.

So for copying here you'd use a for loop or memcpy().

I've used C compilers where that would compile just fine...and when run the code would make x point to y's array.

You see, in C the name of an array is a pointer that points to the start of the array. In fact, arrays and pointers are essentially interchangable. You can take any pointer and index it like an array.

Back when C was being developed in the early 70's, it was meant for relatively small programs that were barely above assembly language in abstraction. In that environment, it was damn handy to be able to easily go back and forth between array indexing and pointer math. Copying whole arrays of data, on the other hand, was a very expensive thing do do, and hardly something to be encouraged or abstracted away from the user.

Yes, in these modern times it would make way more sense to have the name of the array be shorthand for "the whole array", rather than for "a ponter to the front of the array". However, C wasn't designed in these modern times. If you want a language that was, try Ada. x := y there does exactly what you would expect; it copies one array's contents to the other.

Category:c# Time:2009-04-13 Views:1

Related post

  • PLPGSQL array assignment not working, "array subscript in assignment must not be null" 2010-12-24

    When assigning mobilenumbers to a varchar[] in a loop through results it gives me the following error: "array subscript in assignment must not be null" Also, i think the query that joins member uuids, and group member uuids, into one, grouped on the

  • Java problems with moving class objects into an array. Not sure if there is a fault with the constructors or the array declaration 2011-07-23

    Having a bit of trouble moving objects I've created into an array. So what I actually need to do is create objects than move them into an array. I'm not quite sure what I'm doing wrong. If you think I should be using a arraylist instead of a array pl

  • An array declared ouside the method(at class level), and assgned values inside a method doesn't work. Why? 2011-08-23

    *I made an array.. at the class level,but assigned it's values inside a method.. but for some reason.. it gave up an error.. then when i did the array declaration & assignment inside of the same method.. everything functioned smoothly!! Why is th

  • how to declare the sysconf return value in global array declaration? 2012-01-30

    I wrote a program for maintaining all open file descriptor details . So, I used sysconf function to get the runtime max open file descriptor to be allowed . if array declaration is not in the global means it doesn't say any error .its work fine. This

  • Cant retrieve PHP arrays outside the assigning loop 2012-05-02

    I am trying to create a 2-dimensional array, reading specific values from a (large) met file. The arrays are empty and I dont know why. I have the following array: $varmet = array('tasmax', 'tasmin', 'pr', 'clt'); I have two loops: The first is for (

  • How to deal with arrays (declared on the stack) in C++? 2008-09-10

    I have a class to parse a matrix that keeps the result in an array member: class Parser { ... double matrix_[4][4]; }; The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interfac

  • c++ array declaration in a header 2008-11-26

    I was wondering if it is possible to declare an array (size not known at this time), as a private member of a class and later set the size in the constructor of the class. For example: class Test { int a[]; public: Test(int size); }; Test::Test(int s

  • Java Array Declaration Bracket Placement 2009-07-09

    I'm trying to print "Hello World" from a Java program, but I am a little confused with the main method: public static void main(String[] args) and public static void main(String args[]) Both these functions perform the same task. How does this happen

  • Strange string array declaration Syntax 2010-01-11

    private final String[] okFileExtensions = new String[] { "csv" }; Would someone please explain why {} is written after a String array declaration? Thanks. --------------Solutions------------- It's an array of one element. In this case containing the

  • ANSI-C grammar - array declarations like [*] et alii 2010-02-22

    The ANSI C grammar from -link- give me the following rules for array declarations: (1) | direct_declarator '[' type_qualifier_list assignment_expression ']' (2) | direct_declarator '[' type_qualifier_list ']' (3) | direct_declarator '[' assignment_ex

  • C programming, why does this large array declaration produce a segmentation fault? 2010-06-16

    This code produces a segmentation fault during the array declaration. I'm confused as to why this happens. I intentionally selected 2000000000 as a value because it is below 2^31 and can fit into an integer variable. int main() { int nums_size = 2000

  • Can I simultaneously declare and assign a variable in VBA? 2010-07-15

    I'm new to VBA and want to know if I can convert the following declaration and assignment into one line: Dim clientToTest As String clientToTest = clientsToTest(i) or Dim clientString As Variant clientString = Split(clientToTest) --------------Soluti

  • Array declarator in Fortran with no lower bound and upper bound 0 2011-03-09

    According to the Fortran standards information I could find (F77,F90/95) an array declarator where there is no lower bound assumes that this lower bound is 1. As the upper bound needs to be larger than or equal to the lower bound, this would make the

  • Question about a funky array declaration 2011-04-10

    I just came across this array declaration: const int nNums= 4; int* nums[nNums] = {0, 0, 0}, d[nNums]; I understand that a pointer to nums is being created, but what is the business on the right? d[] gets initialized, but I am not quite sure what the

  • Specify the element position in the array declaration in C++ 2011-06-29

    In C it is often very helpful to specify the element position when doing an array declaration. eg: int appliance_id_from_mode[] = { [MASTER] = 0, [SLAVE] = 1 }; This declaration verbatim does not seem to work in c++ ( or at least g++ ), is there any

  • Writing an array declaration string 2011-07-15

    I am working on a tool that writes java files. At a given point I have to write an array declaration. I have implemented the following methods: public static String arrayToCode(Long[] arr, String arrName) { StringBuilder sb = new StringBuilder(); sb.

  • Array declaration in the .h file, is it a good idea? 2011-07-20

    I am working in C++ and want to declare an array in the private section of the header file. Now that I am thinking about it, I thought doing so was bad practice? I would think doing this would cause multiple declarations everywhere the header is incl

  • 3d array declaration causes segmentation fault 2011-11-11

    I'm converting a program from fortran to C++. My code seems to run fine until I add this array declaration: float TC[100][100][100]; And then when I run it I get a segmentation fault error. This array should only take up 8Mb of memory and my machine

  • If statement within an array declaration -is that possible? 2011-11-30

    Possible Duplicate: A conditional element inside an array(…) construct Here is my code $product_option_value_data[] = array( 'product_option_value_id' => $product_option_value['product_option_value_id'], if (isset($product_option_value_description

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.501 (s). 13 q(s)