Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give values to arrays in c

Tags:

c

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.

like image 407
Nilesh Agrawal Avatar asked Jul 17 '13 01:07

Nilesh Agrawal


People also ask

How do you give values to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Can you add values to an array in C?

If you have a code like int arr[10] = {0, 5, 3, 64}; , and you want to append or add a value to next index, you can simply add it by typing a[5] = 5 .

What is the value of an array in C?

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one. In the example above the subscripts run from 0 through 5.


1 Answers

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.

like image 154
Sergey Kalinichenko Avatar answered Nov 15 '22 05:11

Sergey Kalinichenko