Array entries being overwriten in C

how to overwrite an array in c
php merge array values with same keys
strcpy
php combine array keys and values
array combine
php merge multidimensional array
php merge array with same values
array_merge_recursive

I want to convert an integer array to a string array. For example, if arr[] = {1, 2, 3, 4, 5}, I want to end up with arr2[] = {"1", "2", "3", "4", "5"}. This function works fine until it exits the for loop where all the array entries are being overwritten with the value of the last entry. Any idea as to why this might be happening?

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

#define SIZE 5
int main(){
    int nums[] = {1, 2, 3, 4, 5};
    char **strings = (char **)malloc(SIZE * sizeof(char*));

    for(int i = 0; i < SIZE; i++){
        char temp[20];
        sprintf(temp, "%d", nums[i]);
        strings[i] = temp;
        //prints correct values here
        printf("%s\n", strings[i]);
    }

    for(int i = 0; i < SIZE; i++){
        //prints wrong values here
        printf("%s\n", strings[i]);
    }

    free(strings);
    return 0;
}

The issue is strings[i] = temp;. This assigns temp to strings[i], but then temp is a local variable scoped to the loop block, and is not valid after the block terminates.

You'll need to malloc memory for each string to hold the copied value (and free it when done). tmp is also unnecessary since we can sprintf directly into the pointer.

SIZE = 5 but your array only has 4 members, so we have an out of bounds access. I'd prefer to scope this to the data it represents rather than make it a global constant. I'm also assuming this array will handle arbitrary data, because as-is, there's no advantage to it over using i + 1 inside your loop.

malloc(12) is sufficient space to hold a 32-bit int string (sizeof char is always 1 and we need space for '-' and '\0' characters). As pointed out in this comment, you can use sizeof(int) * CHAR_BIT / 3 + 2 to compute the correct size for the buffer where CHAR_BIT is defined in the limits.h header.

As an aside, there's no need to cast malloc and it's good practice to use sizeof(*strings) in case the pointer type changes during a refactor.

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

int main() {
    int nums[] = {1, 2, 3, 4};
    int nums_size = 4;
    char **strings = malloc(nums_size * sizeof(*strings));

    for (int i = 0; i < nums_size; i++) {
        strings[i] = malloc(12);
        sprintf(strings[i], "%d", nums[i]);
    }

    for (int i = 0; i < nums_size; i++) { 
        printf("%s\n", strings[i]);
        free(strings[i]);
    }

    free(strings);
    return 0;
}

Array Elements Overwritten, The first iteration of my for loop over the paths array works fine - but then contents of the paths array are being overwritten/turned to garbage. Array Elements Overwritten I have the following function in a tiny C app. I basically take in an array of directory paths (the "paths" argument) and, for each path, iterate over each file in the directory and print the file name.

Always let the compiler do counting for you.

First, I define below a macro COUNTOF that produces the number of items (not the number of bytes) in the array object; that should be used everywhere.

Second, the strdup() library function makes a copy of a string buffer - it counts the length, allocates the right number of bytes, then copies the string into it. Much easier than rolling your own.

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

#define COUNTOF(x)   ( sizeof(x) / sizeof((x)[0]) )

int main(){
    int nums[] = {1, 2, 3, 4};
    char **strings = malloc(COUNTOF(nums) * sizeof(*strings));

    for(int i = 0; i < COUNTOF(nums); i++){
        char temp[40];  // bigger than any plausible int
        sprintf(temp, "%d", nums[i]);
        strings[i] = strdup(temp);   // HERE
        printf("%s\n", strings[i]);
    }

    for(int i = 0; i < COUNTOF(nums); i++){
        //now prints correct value here :-)
        printf("%s\n", strings[i]);
    }

    return 0;
}

Updating Array Values Incrementally Overwrites The Existing Values , That points to assign for every element in response[] . C/C++ Arrays don't work the way you are used from scripting languages. In your loop you have a array of char assign[5] that gets assigned to every single of those� Converting C# ideas to C++ (part 2) file problem ; Searching Through an array. Infinte Loop with Reading a file? why i cant write records into file in turbo-pascal??? Linear Search - pascal HELP! Sorting an ArrayList of objects by a variable. Searching for a number in an array ; sorting an array in PASCAL ; PASCAL

There's actually no need to do this in run-time. You can do this at compile time if you can suffer some "X macro" tricks.

#define INIT_LIST \
   X(1) \
   X(2) \
   X(3) \
   X(4) \

#define STR(n) #n

#include <stdio.h>

int main (void)
{
  #define X(n) n,
    int nums[] = {INIT_LIST};
  #undef X

  #define X(n) STR(n),
    const char* str[] = {INIT_LIST};
  #undef X

  for(size_t i=0; i<sizeof(nums)/sizeof(*nums); i++)
  {
    printf("%d %s\n", nums[i], str[i]);
  }
}

Where INIT_LIST has to contain all the initializers as integers. After pre-processing, the above expands to this:

#include <stdio.h>

int main (void)
{
  int nums[] = {1,2,3,4};
  const char* str[] = {"1", "2", "3", "4"};

  for(size_t i=0; i<sizeof(nums)/sizeof(*nums); i++)
  {
    printf("%d %s\n", nums[i], str[i]);
  }
}

Performance-wise, this is naturally going to be astronomically faster than any solution using heap allocation. The down side is that X macros can be a bit hard to read.

Problem with C string array overwriting values, The problem is that the last argument is writes over all indexes of the array. I'm newer to C programming. #include <stdio.h> #include <string.h> #include� so I have an array that keeps getting overwritten with new values. For example, this is the output: instruc[0] = PRINTNUM instruc[1] = PRINTNUM instruc[2] = PRINTNUM where PRINTNUM is supposed to be the last thing in the array and the first two elements are supposed to be something else. Here is my code for the specific segment:

array_merge - Manual, If, however, the arrays contain numeric keys, the later value will not overwrite the original Values in the input arrays with numeric keys will be renumbered with $c = array_merge($a, $b); // shows a PHP warning: Argument #2 is not an array Multi-dimensional arrays. C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2: Passing arrays to functions. You can pass to the function a pointer to an array by specifying the array's name without an index. 3: Return array from a function. C allows a function to return an array. 4

[C] Array Pointers in Structs are being Overwritten for all Structs of , [C] Array Pointers in Structs are being Overwritten for all Structs of the Same Type method are overwriting the data for all of the (struct objects?) being created. values being a vector of ints. The method itself seems to work fine, however, debugger shows that everytime I invoke the method with new Item, the previous values already put in my array are set to the same values as the new item. (ex. if items[0] has value of 5, and I invoke the method with an item valued as 10, the items[0] instantly is set

Array.Copy Method (System), WriteLine( "Object array - First element should now be the same as Int32 array:" ); before destinationArray is overwritten. [C++]. This method is equivalent to the� LCD Custom Character Arrays Being Overwritten? Apr 02, 2020, 08:09 pm Last Edit : Apr 02, 2020, 08:14 pm by poor_red_neck I have some custom characters in an array setup, but they are being overwritten.

Comments
  • temp is a local variable inside the loop. Each iteration it goes out of scope and its life-time will end. All your pointers will be to this array, so after the loop all your pointers will be invalid. Using it in any way will lead to undefined behavior.
  • Your temp is living only one iteration.
  • Not to mention that you iterate five times over an array containing only four elements.
  • @Someprogrammerdude yeah that was a mistake on my part the array is supposed to be {1, 2, 3, 4, 5}
  • Then please edit your question to fix it. A minimal reproducible example with unrelated errors and problems will distract from the actual problem you ask about.
  • Thanks for the help and advice, your solution worked best for what I'm trying to do!
  • And @ggorlen correctly reminds you to free memory when you're done with it.
  • Aside: char temp[20]; is OK for 32 bit math. Another is char temp[sizeof(int)*CHAR_BIT/3 +2]; or some other similar self-scaling buffer size.
  • Good point; it's 21 bytes to support 64-bit stuff, so there's no harm in just making it 40.
  • When I'm looking for quick coding and do not want to compute the buffer need, I think of a likely worst case to support, like int128, and then double it.
  • Please note that strdup isn't standard C.