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; }
๐ŸŒ
YouTube
youtube.com โ€บ watch
Find and Replace Elements in 1-D Array using C programming | by Sanjay Gupta - YouTube
Find Here: Links of All C language Video's Playlists/Video SeriesC Interview Questions & Answers | Video Serieshttps://www.youtube.com/watch?v=UlnSqMLX1tY&li...
Published ย  February 13, 2018
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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 ยท
๐ŸŒ
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
Find elsewhere
๐ŸŒ
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 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.
๐ŸŒ
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 ...
๐ŸŒ
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] ...
Top answer
1 of 2
1
#include <stdio.h>
#include <stdint.h>

#define DATA_SIZE 6

int main(void){
    char userInput[256];
    int inputNum, winningNumbers[DATA_SIZE];
    uint64_t table = 0;
    int i=0;
    while(i<DATA_SIZE){
        printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
        fgets(userInput, sizeof(userInput), stdin);
        if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
            continue;
        uint64_t bit = 1 << inputNum;
        if(table & bit)
            continue;
        table |= bit;
        winningNumbers[i++] = inputNum;
    }
    for(i=0;i<DATA_SIZE;++i)
        printf("%d ", winningNumbers[i]);
    printf("\n");
    return 0;
}
2 of 2
0
#include <stdio.h>
#include <stdlib.h>

#define DATA_SIZE 6

int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
    char inputLine[256];
    int n;

    for(;;){
        printf("%s", msg);
        fgets(inputLine, sizeof(inputLine), stdin);
        if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
            fprintf(stderr, "%s", errMsg);
        else
            return n;
    }
}

int inputNumber(void){
    return inputNumberWithRangeCheck(
        "\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
        "Invalid Input.\n",
        1,49);
}

int *inputArray(int *array, size_t size){
    int i;
    for(i=0;i<size;++i){
        printf("\nInput for No.%d\n", i+1);
        array[i] = inputNumber();
    }
    return array;
}

int **duplicateCheck(int *array, size_t size){
    int **check, count;
    int i, j;

    check = malloc(size*sizeof(int*));
    if(!check){
        perror("memory allocate\n");
        exit(-1);
    }
    //There is no need to sort the case of a small amount of data
    //(Cost of this loop because about bubble sort)
    for(count=i=0;i<size -1;++i){
        for(j=i+1;j<size;++j){
            if(array[i] == array[j]){
                check[count++] = &array[i];
                break;
            }
        }
    }
    check[count] = NULL;
    if(count)
        return check;
    else {
        free(check);
        return NULL;
    }
}

int main(void){
    int winningNumbers[DATA_SIZE];
    int **duplication;
    int i, j;

    inputArray(winningNumbers, DATA_SIZE);

    while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
        for(i=0;i<DATA_SIZE;++i){
            if(duplication[i]){
                printf("\nyour input numbers : ");
                for(j=0;j<DATA_SIZE;++j)
                    printf("%d ", winningNumbers[j]);
                fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
                *duplication[i] = inputNumber();
            } else
                break;
        }
        free(duplication);
    }
    for(i=0;i<DATA_SIZE;++i)
        printf("%d ", winningNumbers[i]);
    printf("\n");
    return 0;
}
๐ŸŒ
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.
๐ŸŒ
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 ...
๐ŸŒ
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).
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ cplusplus-program-to-replace-an-element-makes-array-elements-consecutive
C++ program to replace an element makes array elements consecutive
August 10, 2022 - #include <iostream> #include <vector> #include <algorithm> using namespace std; int solve(vector<int> arr) { sort(arr.begin(), arr.end()); int n = arr.size(); int mismatch = 0, ans; int nextElement = arr[n-1] - n + 1; for (int i=0; i<n-1; i++, nextElement++) { if (binary_search(arr.begin(), arr.end(), nextElement) == 0) { ans = arr[0]; mismatch++; } } if (mismatch == 1) return ans; if (mismatch == 0) return 0; mismatch = 0; nextElement = arr[0] + n - 1; for (int i=n-1;i>=1;i--, nextElement--) { if (binary_search(arr.begin(), arr.end(), nextElement) == 0) { ans = arr[n-1]; mismatch++; } } if (m
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)

Top answer
1 of 3
2

Never iterate further than the array length. This leads to undefined and possibly dangerous behaviour. If you only expect strings, use something like:

int i = 0; 
while(output[i] != '\0')
{
    // your logic here
    i++;
}

Additionally you want to check for concurrent appearances of the same characters. But in your code you only check the first three characters. Everything after that is undefinded behaviour, because you cannot know what replace[3] returns.

Something similar to this could work:

int i = 0;
int j = 0;
int k;
while(output[i] != '\0')
{
    if (output[i] == replace[j])
        j++;
    else
        j = 0;
    // replace 3 with the array length of the replace[] array
    if (j == 3)
    {
        for(k = i; j >= 0; k-- )
        {
            output[k] = toBeReplacedBy[j]
            j--
        }
        j = 0;
    }
    i++;
}

But please check the array boundaries.

edit: Additionally as Nellie states using a debugger would help you to understand what went wrong. Go through your program step by step and look how and when values change.

2 of 3
0

First advice is to try to debug your program if it does not work.

for (i = 0; i<80; i++) {
        if (output[i] == replace[i])
            output[i] = toBeReplacedBy[i];
    }

There are two problems in this loop.

The first is that are iterating until i is 80. Let's look what happens when i becomes 3. output[3] in case of abcdefabc is d, but what is replace[3]? Your replacement array had only 3 letters, so you have to go back in the replacement array once you finish with one occurrence of it in the original string.

The second is that you check letter by letter.

Say you original array, which you named output somehow was abkdefabc, first three letters do not match your replacement string, but you will check the first two letters they will match with the replacement's first two letters and you will incorrectly change them.

So you need to first check that the whole replacement string is there and only then replace.