5

I am getting error in the following program. I am unable to figure out why I am not able to store values in the array

main()
{
    int A[10];
    A = {3,1,2,3,4,1,5,8,9,0};
    printArr(A,10);
    printf("\n");

    BubbleSort(A,10);

    printArr(A,10);
    printf("\n----------------Bubble Sort Efficiently ---------------------\n");
    printf("\n");

    A = {3,1,2,3,4,1,5,8,9,0};

    BubbleSortEfficient(A,10);
    printArr(A,10);

    return 0;
}

This is the error I got:

73: error: expected expression before ‘{’ token
80: error: expected expression before ‘{’ token

Please clarify with reason why I am not able to store array elements.

doubleDown
  • 8,048
  • 1
  • 32
  • 48
Nilesh Agrawal
  • 3,002
  • 10
  • 26
  • 54

4 Answers4

9

ANSI C does not have a syntax for defining array aggregates outside of array initializers. If you combine initialization with the assignment (which technically is not an assignment, but part of initialization) your code will compile:

int A[10] = {3,1,2,3,4,1,5,8,9,0};

Since you cannot reassign arrays, the portion of your program before the second call of BubbleSortEfficient should look like this:

int B[10] = {3,1,2,3,4,1,5,8,9,0};
BubbleSortEfficient(B, 10);
printArr(B, 10);

EDIT : (in response to comment by Keith Thompson) C99 introduces array aggregate expressions, but they cannot be assigned to arrays, because the standard does not have array assignments.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

Curly braces are used for initialization, not assignment. You should be able to do this:

int A[10]={3,1,2,3,4,1,5,8,9,0};
johnchen902
  • 9,531
  • 1
  • 27
  • 69
Omegaman
  • 2,189
  • 2
  • 18
  • 30
4

You cannot assign directly to an array, because an array is not a modifiable lvalue. However, if you enclose an array with a structure, then you can assign to a structure.

struct array {
    int a[10];
};

const struct array x = { {3,1,2,3,4,1,5,8,9,0} };
struct array A;
A = x;
BubbleSort(A.a,10);
A = x;
BubbleSortEfficient(A.a,10);

Or, you can use the more traditional memcpy():

int A[10];
memcpy(A, (int[]){3,1,2,3,4,1,5,8,9,0}, sizeof(A));
jxh
  • 69,070
  • 8
  • 110
  • 193
0

yes you can not assign values to the array like this. You have to assign it as follows,

'int A[10]={3,1,2,3,4,1,5,8,9,0};'

Parthiv Shah
  • 350
  • 3
  • 17