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 - 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
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, Write a C program to replace an element in an array with its position
๐ŸŒ
w3resource
w3resource.com โ€บ c-programming-exercises โ€บ array โ€บ c-array-exercise-63.php
C Program: Replace every element with the greatest one
Write a program in C to replace every element with the greatest element on its right side. Expected Output : The given array is : 7 5 8 9 6 8 5 7 4 6 After replace the modified array is: 9 9 9 8 8 7 7 6 6 0
๐ŸŒ
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 use a loop and conditional statements to substitute negative and zero values in an array with 1. Write a C program to modify an array by scanning each element and replacing invalid (<=0) numbers with 1.
๐ŸŒ
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 ...
๐ŸŒ
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
C program to replace all EVEN elements by 0 and Odd by 1 in One Dimensional Array - C programming Example. This example will read array and replace all even and odd numbers by 0 and 1 respectively.
๐ŸŒ
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 - Given an array arr, the task is to replace each element of the array with the element that appears before it and replace the first element with -1. ... Approach: Traverse the array from n - 1 to 1 and update arr[i] = arr[i-1]. In the end set a[0] = -1 and print the contents of the updated array.
๐ŸŒ
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] = -1 and print the contents of the updated array.
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 - I have a one-dimensional array in which I need to replace the elements of the array after the smallest element with one and find the sum of all the el
๐ŸŒ
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 - Sort the copied array. Run a nested loop and find the position of the given array element in the sorted array. And replace the element with the position.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 33109023 โ€บ loop-to-replace-element-in-an-array
c - Loop to replace element in an array - Stack Overflow
I'm trying to "delete" an element from my struct and move the rest of my arrays below it up so it doesn't show a gap. I can't, unfortunately, paste the code that I am using here. My teacher will be
๐ŸŒ
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 - Create the two series mentioned above, and then find each series' elements in the array. If there are more than one mismatches between the two series, then impossible. If one mismatch can be detected in any sequence, we have the answer. Implementing a C++ program below, that replaces an array ...
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.