In C99 you can assign each structure in a single line. I don't think that you can assign the array of structs in one line though.

C99 introduces compound literals. See the Dr. Dobbs article here: The New C: Compound Literals

theTest[0] = (test_t){7,8,9};
theTest[1] = (test_t){10,11,12};

You could assign to a pointer like this:

test_t* p; 
p = (test_t [2]){ {7,8,9}, {10,11,12} };

You could use memcpy as well:

memcpy(theTest, (test_t [2]){ {7,8,9}, {10,11,12} }, sizeof(test_t [2]);

Above tested with gcc -std=c99 (version 4.2.4) on linux.

You should read the Dr. Dobbs article to understand how compound literals work.

Answer from Karl Voigtland on Stack Overflow
๐ŸŒ
Quora
quora.com โ€บ How-can-you-change-all-values-in-an-array-without-using-loops
How to change all values in an array without using loops - Quora
Answer: Every programming language supporting arrays allows you to change any single value in an array without a loop. The C programming language allows array values to be initialized using an initializer list: [code]int arr[5] = {1,2,3,4,5}; [/code]You can then change the values of each elemen...
Top answer
1 of 8
47

For your specific case where you initially have 0 and 1, the following might be faster. You'll have to bench mark it. You probably can't do much better with plain C though; you may need to dive into assembly if you want to take advantage of "x86 trickery" that may exist.

for(int i = 0; i < size ; i++){
  array[i] *= 123456;
}

EDIT:

Benchmark code:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

size_t diff(struct timespec *start, struct timespec *end)
{
  return (end->tv_sec - start->tv_sec)*1000000000 + end->tv_nsec - start->tv_nsec;
}

int main(void)
{
  const size_t size = 1000000;
  int array[size];

  for(size_t i=0; i<size; ++i) {
    array[i] = rand() & 1;
  }

  struct timespec start, stop;

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
  for(size_t i=0; i<size; ++i) {
    array[i] *= 123456;
    //if(array[i]) array[i] = 123456;
  }
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);

  printf("size: %zu\t nsec: %09zu\n", size, diff(&start, &stop));
}

my results:

Computer: quad core AMD Phenom @2.5GHz, Linux, GCC 4.7, compiled with

$ gcc arr.c -std=gnu99 -lrt -O3 -march=native
  • if version: ~5-10ms
  • *= version: ~1.3ms
2 of 8
15

For a small array such as your it's no use trying to find another algorithm, and if the values are not in a specific pattern a simple loop is the only way to do it anyway.

However, if you have a very large array (we're talking several million entries), then you can split the work into threads. Each separate thread handles a smaller portion of the whole data set.

๐ŸŒ
Quora
quora.com โ€บ How-can-I-change-the-values-of-an-array-with-a-void-function-in-c
How to change the values of an array with a void function in c - Quora
Answer (1 of 6): There are two ways. 1. Suppose if the array is declared as global. You could simply change the values of array by assignment. 2. If the array your are talking about is not declared as global then pass the address of the array. To do that use & operator. Eg foo(&myarray). Once yo...
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 32620-change-value-array.html
Change Value in an array
January 18, 2003 - Remember, indexes in C range from 0 to n-1, where n is 6 here. ... View Forum Posts .... ... >score=array[selection1]; This assigns the value of the element of array with index selection1 to score. This array[selection1] = score; assigns the value of score to the element of the array with index selection1. ... All times are GMT -6.
Top answer
1 of 10
31

In c you can't pass a variable by reference, the array variable that you assign inside the function contains initially the same address as the passed pointer, but it's a copy of it so modifying it will not alter the passed pointer.

You need to pass the address of the pointer in order to be able to alter it, like this

// Change the pointer of the array
void change(int **array, int length)
{
    *array = malloc(length * sizeof(int));
    if (*array == NULL)
        return;
    for (int i = 0 ; i < length ; i++)
        (*array)[i] = 1;
}

Then in main() you cannot assign to an array, doing so through this kind of function is surely undefined behavior. The array defined in main() is allocated on the stack and you cannot assign anything to an array since they are non-writeable lvalues so you cannot make it point to a heap memory location obtained with malloc(), you need to pass a pointer like this

int *array;
change(&array, length);
free(array);

If you want the function to replace the previous array, it will have to free() the malloc()ed data (note that passing NULL to free() is well defined), so

// Change the pointer of the array
void change(int **array, int length)
{
    free(*array);

    *array = malloc(length * sizeof(int));
    if (*array == NULL)
        return;
    for (int i = 0 ; i < length ; i++)
        (*array)[i] = 1;
}

then in main()

int *array;
array = NULL;
change(&array, length);
change(&array, length);
change(&array, length);
change(&array, length);
free(array);

will do what you apparently want.

2 of 10
3

Ok, i will make the answer short.

  1. Arrays are always passed by reference in C

change(array, length); In this line, it means reference to the first element of the array variable is passed to the function.

Now the function needs a pointer to catch the reference, it can be a pointer or it can be an array. Note that the pointer or the array is local to the function.

  1. You received it in a pointer named array. Which is definitely a pointer but it is not the same as array in main function. It is local to the change function.

  2. You declared a new array dynamically, and assigned a pointer named new with it. And all the changes you did were to new pointer.

Everything is ok till now.

  1. Now you assigned the new pointer to the array pointer which is local to the change function.

This is the real issue. As even though the array is in heap section, and it will remain in the memory, but the *array and *new are local pointer variables.

Also array pointer in change function is different from array pointer in main function.

  1. The solution to this problem is Manipulate the data of array pointer directly.

    void change(int *array,int length) { int i; for(i = 0 ; i < length ; i++) array[i] = 1; }

In this way you are directly overwriting values of array in main function. Everything else is correct.

Summerization: array pointer in change function is local to change function. array in main function is local to main function. Making change function's local array pointer point to array in heap section won't change data in actual array. You changed pointer's position, Not the array's data.

๐ŸŒ
YouTube
youtube.com โ€บ watch
How To Replace Elements Of Array in C / C++ - YouTube
c program to update an element in an arrayc++ program to replace an element in an arrayhow to change values in an array c++modify array in function carray up...
Published ย  December 21, 2017
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ replace-every-element-of-the-array-by-its-previous-element
Replace every element of the array by its previous element - GeeksforGeeks
September 12, 2022 - // C program to replace every element ... every element // of the array with the element that appears before it void updateArray(int arr[], int n) { // Update array for (int i = n - 1; i > 0; i--) arr[i] = arr[i - 1]; // Change ...
Find elsewhere
๐ŸŒ
Zhu45
zhu45.org โ€บ posts โ€บ 2017 โ€บ Jan โ€บ 08 โ€บ modify-array-inside-function-in-c
Modify array inside function in C - Zeyuan Hu's Page
Then, we check the value hold by that address, which is expected 1 the first element of our test array. Our goal is to let test array in test_change3() be 5,5,5: Before change3 +---+---+--+ test ---------> | 1 | 2 | 3| +---+---+--+ +---+---+--+ tmp ---------> | 5 | 5 | 5| +---+---+--+ After change3 +---+---+--+ tmp ---------------> | 5 | 5 | 5| /-> +---+---+--+ test(array) ------- From the picture we can see that we want to modify array inside change3 pointing to 5,5,5 and this change will persist to the test array in our caller function.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 65834
Changing all values of an array? - C++ Forum
Not like that. You can use memset to set all the values of an array at once but it sets them all to the same value. You're going to need to make a nested loop to go through every element in the array.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 66040737 โ€บ how-to-change-the-value-in-char-array
c - How to change the value in char *array[]? - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I have an array(Array) and the value define as char array (LIST) in another .h file. char *Array[]= { "something1", "something2", "something3" }; LIST is defined in .h file. ... If I would like to change all values in Array to be LIST.
๐ŸŒ
Quora
quora.com โ€บ How-can-I-update-an-element-in-an-array-using-C
How to update an element in an array using C - Quora
Answer (1 of 4): Add this line to the beginning of your code [code]#define update(arr,pos,val) do{arr[pos]=val;}while(0) [/code]You will have to use it like this [code]update(name_of_array, position, new_value); [/code]For example: [code]#define update(arr,pos,val) do{arr[pos]=val;}while(0) #i...
๐ŸŒ
w3resource
w3resource.com โ€บ c-programming-exercises โ€บ basic-declarations-and-expressions โ€บ c-programming-basic-exercises-51.php
C Program: Print the elements of the modified array - w3resource
Write a C program to read an array of length 6, change the first element by the last, the second element by the fifth and the third element by the fourth. Print the elements of the modified array. ... #include <stdio.h> #define AL 5 int main() { // Define the size of the array int array_n[AL], i, temp; // Prompt user to input 5 elements of the array printf("Input the 5 members of the array:\n"); for(i = 0; i < AL; i++) { scanf("%d", &array_n[i]); } // Swap the first half of the array with the second half for(i = 0; i < AL; i++) { if(i < (AL/2)) { temp = array_n[i]; array_n[i] = array_n[AL-(i+1)]; array_n[AL-(i+1)] = temp; } } // Print the modified array for(i = 0; i < AL; i++) { printf("array_n[%d] = %d\n", i, array_n[i]); } return 0; }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ changing-array-inside-function-in-c
Changing Array Inside Function in C - GeeksforGeeks
July 23, 2025 - // C Program to change an Array in function #include <stdio.h> // here 'm' is the formal argument void addval(int m[]) { int i; for (i = 0; i < 5; i++) { // adding 10 value to each element // of an array m[i] = m[i] + 10; } } // here 'm' is the formal argument void dis(int m[]) { int i; for (i = 0; i < 5; i++) { printf("%d ", m[i]); } printf("\n"); } void main() { int a[] = { 11, 12, 13, 14, 15 }; printf("Array before function call\n"); // function call dis(a); // calling addval function addval(a); printf("Array after function call\n"); dis(a); }
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 40047348 โ€บ modify-all-elements-of-an-array-at-the-same-time
c - Modify all elements of an array at the same time - Stack Overflow
Copyfunction setCOD7DecodeFx() { alphabet = strTok("a b c d e f g h i j k l m n o p q r s t u v w x y z", " "); test = "text"; is_done = false; //I want all of the letters of text to change at the same time while(!is_done) { //I want this to happen without having to do text[num] test[0] = alphabet[rand(0, alphabet.size - 1)]; test[1] = alphabet[rand(0, alphabet.size - 1)]; //rand -> rand(min, max) test[2] = alphabet[rand(0, alphabet.size - 1)]; //alphabet.size -> counts all elements in an array test[3] = alphabet[rand(0, alphabet.size - 1)]; wait 0.25; } wait 3; is_done = true; test = "text"; }
Top answer
1 of 1
12

Version 1:

#include <stdio.h>
#define MAX 20
typedef int Values[MAX];

int changeArr(int vals2[]) {
    vals2[0] = 200;
    vals2[1] = 100;
    printf("%d and ", vals2[0]);
    printf("%d\n", vals2[1]);
    return 0;
}   

int main (int argc, char *argv[]) {

    Values vals;
    changeArr(vals);
    printf("%d and ", vals[0]);
    printf("%d\n", vals[1]);
    return 0;

}

Instead of passing a pointer to the array, pass a pointer to the array's first element.

Version 2:

#include <stdio.h>
#define MAX 20
typedef int Values[MAX];

int changeArr(Values *vals2) {
    (*vals2)[0] = 200;
    (*vals2)[1] = 100;
    printf("%d and ", (*vals2)[0]);
    printf("%d\n", (*vals2)[1]);
    return 0;
}   

int main (int argc, char *argv[]) {

    Values vals;
    changeArr(&vals);
    printf("%d and ", vals[0]);
    printf("%d\n", vals[1]);
    return 0;

}

use parentheses to compensate for the precedence.

The problem in your code is that

*vals2[1]

is *(vals2[1]), so it dereferences a pointer one unit of Values after the passed pointer. You have no accessible memory allocated there, so it's undefined behaviour. In practice, it is the same as accessing

arr[1][0]

for an

int arr[2][MAX];

But your vals is only (equivalent to) an int arr[1][MAX];, so you are accessing out of bounds. But if nothing worse happens, *vals2[1] = 100; in changeArr sets vals[MAX] in main to 100. It may overwrite something crucial, though.

In int changeArr(Values *vals2) you are passing a pointer to an array of MAX ints, resp the first such array in an array of Values. Then vals2[1] is the second array in that array of Values (which doesn't exist here), and *vals2[1] == vals2[1][0] the first int in that second array. You want to modify elements of the first (and only) array in the pointed-to memory block, so you want to access vals2[0][1], or equivalently (*vals2)[1].

A picture:

vals2                          vals2[1]
 |                               |
 v                               v
|vals[0]|vals[1]|...|vals[MAX-1]|x

in changeArr, the pointer vals2 points to the array vals. Since it's a pointer to an int[MAX], vals2+1 points to an int[MAX] at an offset of MAX*sizeof(int) bytes after the start of vals (which is just behind the end of vals). vals2[1], or equivalently *(vals2 + 1), is that array just after vals (which doesn't exist).

You want to change vals[1], which is located in the array vals2[0], at an offset of 1*sizeof(int) bytes, so you need vals2[0][1] or equivalently (*vals2)[1].

๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 180878
Change elements in an array - C++ Forum
The third is supposed to be a bool function to receive the position of the array to modify and assign the new value to that position. The last function is supposed to be another bool function to clear either a single element or every element in the array. I was wondering if you guys could help me out with these four functions in any way cause I'm totally lost. ... Similar to the last one. How might you change the value in the array once you found it?