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
Answer from Nicu Stiurca on Stack Overflow
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.

๐ŸŒ
CodeCrucks
codecrucks.com โ€บ home โ€บ programs โ€บ c program to replace array elements by given value
C Program to Replace Array Elements by Given Value - CodeCrucks
March 23, 2023 - // C Program to Replace Array Elements by Given Value #include <stdio.h> int main() { int A[] = {1, 6, 5, 8, 6}, n, k, i, j, flag=0; n = sizeof(A) / sizeof(A[0]); printf("Array A :--> "); for(i=0; i<n; i++) printf("%d ", A[i]); printf("\nEnter the Element to replace :--> "); scanf("%d", &k); for(i = 0;i < n; i++) { if(A[i] == k) { int r; flag = 1; printf("Enter Element Replaced with %d:--> ",i); scanf("%d", &r); A[i] = r; } } if(flag == 0) { printf("\nThe element not found in the array"); } else { printf("\nArray After Replacement :--> "); for(j = 0; j < n; j++) { printf("%d ",A[j]); } } return 0; } Output: Run 1: Array A :--> 1 6 5 8 6 Enter the Element to replace :--> 3 The element not found in the array Run 2: Array A :--> 1 6 5 8 6 Enter the Element to replace :--> 6 Enter Element Replaced with 1:--> 11 Enter Element Replaced with 4:--> 22 Array After Replacement :--> 1 11 5 8 22 ยท
๐ŸŒ
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
๐ŸŒ
SunShine Softwares
sunshinesoftwares.com โ€บ home โ€บ questions โ€บ write a c program to replace an element from an array at specified position.
Write a C Program to replace an element from an array at specified position. - SunShine Softwares
July 15, 2022 - #include<stdio.h> #include <conio.h> void main() { int arr[100],pos,newvalue; int i,n; printf("Enter size of the array : "); scanf("%d", &n); printf("\nEnter array Elements now: "); for(i=0;i<n;i++) scanf("%d", &arr[i]); printf("\nEnter Position of Element : "); scanf("%d", &pos); printf("\nEnter New Value: "); scanf("%d", &newvalue); arr[pos-1]=newvalue; printf("\nModified Elements Are: "); for(i=0;i<n;i++) printf("\n%d", arr[i]); getch(); } ShriRam Changed status to publish July 15, 2022 ยท
๐ŸŒ
IncludeHelp
includehelp.com โ€บ c-programs โ€บ c-program-to-replace-even-and-odd-elements-by-1-and-0.aspx
C program to replace all EVEN elements by 0 and Odd by 1 in One Dimensional Array
**/ void readArray(int arr[], int size) { int i = 0; printf("\nEnter elements : \n"); for (i = 0; i < size; i++) { printf("Enter arr[%d] : ", i); scanf("%d", &arr[i]); } } /** funtion : printArray() input : arr ( array of integer ), size to display ONE-D integer array on standard output device (moniter). **/ void printArray(int arr[], int size) { int i = 0; printf("\nElements are : "); for (i = 0; i < size; i++) { printf("\n\tarr[%d] : %d", i, arr[i]); } printf("\n"); } /** funtion : replaceEvenOdd() input : arr ( array of integer ), size to replace EVEN elements by 0 and ODD elements by 1.
๐ŸŒ
w3resource
w3resource.com โ€บ c-programming-exercises โ€บ array โ€บ c-array-exercise-63.php
C Program: Replace every element with the greatest one
Write a C program to replace every element with the maximum element found to its right using a reverse traversal. Write a C program to update the array in-place by scanning from right to left to find the next greater element.
๐ŸŒ
Codeforhunger
codeforhunger.com โ€บ 2021 โ€บ 05 โ€บ C program to replace array element.html
codeforhunger: C program to replace an element in an array with its position
May 15, 2021 - In these example we will learn how to replace or insert new element in an array. Ex: Write a C program to replace an element in an array with its position, How to write a C program to replace an element from array, C program to insert and replace element from array.
Find elsewhere
๐ŸŒ
w3resource
w3resource.com โ€บ c-programming-exercises โ€บ basic-declarations-and-expressions โ€บ c-programming-basic-exercises-124.php
C : Replace every negative or null element of an array by 1
Write a C program to dynamically allocate an array, check each element, and replace negatives or zeros with 1 before printing. ... PREV : Compute sum of nnn odd numbers starting from mmm.
๐ŸŒ
C For Dummies
c-for-dummies.com โ€บ blog
Modifying an Array | C For Dummies Blog
One of those other programming language features that intrigued me is the ability to slice a chunk of data from an array. Specifically, a question asked in an online forum was how to remove a single element from an array. In C, you can easily replace an element in an array: a[5] = 8 (or whatever).
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 33109023 โ€บ loop-to-replace-element-in-an-array
c - Loop to replace element in an array - Stack Overflow
In my for loop (j = c; j < totalAccs; j++) I have included all of my arrays and int variables(from my struct), and by using strcpy I replace the element c ( the one that I found from calling another function).
๐ŸŒ
PREP INSTA
prepinsta.com โ€บ home โ€บ c program โ€บ c program to replace each element by its rank in the given array
Replace each element by its rank given in array in C
February 24, 2022 - //Write a program to Replace each element by its rank given in array in C #include<stdio.h> int main(){ int arr[] = { 100, 2, 70, 12 , 90}; int n = sizeof(arr) / sizeof(arr[0]); int temp[n]; for(int i=0; i<n; i++) temp[i] = arr[i]; //sort the ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ replace-every-element-of-the-array-by-its-next-element
Replace every element of the array by its next element - GeeksforGeeks
March 23, 2023 - Given an array arr, the task is to replace each element of the array with the element that appears after it and replace the last element with -1. ... Approach: Traverse the array from 0 to n-2 and update arr[i] = arr[i+1]. In the end, set a[n-1] ...
๐ŸŒ
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 ...
Top answer
1 of 7
4

Something else that is not exactly pertinent to your question but is interesting nonetheless, is that although arrays cannot be assigned to, structs containing arrays can be assigned to:

struct test
{
    float someArray[100];
};


struct test s1 = { /* initialise with some data*/ };
struct test s2 = { /* initialise with some other data */ };

s1 = s2; /* s1's array now contains contents of s2's array */

This also makes it possible to return fixed-length arrays of data from functions (since returning plain arrays is not allowed):

struct test FunctionThatGenerates100Floats(void)
{
    struct test result;
    for (int i = 0; i < 100; i++)
        result.someArray[i] = randomfloat();

    return result;
}
2 of 7
2

As others have said, arrays allocated like that are static, and can not be resized. You have to use pointers (allocating the array with malloc or calloc) to have a resizable array, and then you can use realloc. You must use free to get rid of it (else you'll leak memory). In C99, your array size can be calculated at runtime when its allocated (in C89, its size had to be calculated at compile time), but can't be changed after allocation. In C++, you should use std::vector. I suspect Objective-C has something like C++'s vector.

But if you want to copy data between one array and another in C, use memcpy:

/* void *memcpy(void *dest, const void *src, size_t n)
   note that the arrays must not overlap; use memmove if they do */
memcpy(&struct1, &struct2, sizeof(struct1));

That'll only copy the first ten elements, of course, since struct1 is only ten elements long. You could copy the last ten (for example) by changing &struct2 to struct2+10 or &(struct2[10]). In C, of course, not running off the end of the array is your responsibility: memcpy does not check.

You can also you the obvious for loop, but memcpy will often be faster (and should never be slower). This is because the compiler can take advantage of every trick it knows (e.g., it may know how to copy your data 16 bytes at a time, even if each element is only 1 byte wide)

๐ŸŒ
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...
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 181419-replace-elements-array-c-units.html
Replace elements of array C with units
December 26, 2022 - - Declare another variable as int (e.g. indexOfMin) and initialize it with 0. Use it to remember the index of the current min value that you found. - You don't need the Y array. You know now the index of the smallest element and thus, you can perform the replacement in the original array.
๐ŸŒ
Decode School
decodeschool.com โ€บ C-Programming โ€บ Arrays โ€บ C-Program-to-replace-every-element-with-the-greatest-element-on-right-side
C Program to replace every element with the greatest element on right side | C Programming | Decode School
Get array size n and n elements of array, replace every elements with the greatest element located in right side. ... Strongly recommended to Solve it on your own, Don't directly go to the solution given below. #include<stdio.h> int main() { //write your code here }