Search code examples
cpointerscharcalloc

How do I edit a certain char in the following?


So I have the following code:

char *something = (char *) calloc(LENGTH, sizeof(char));

The length is defined as 10. I'm imaging it like this in memory:

| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | \0 |

How would I change [1] without defining the whole char? And then be able to define [2], and so on...

Each change must not affect the previous change!

Thank you!


Solution

  • The length is defined as 10. I'm imaging it like this in memory

    Incorrect. First, there are only 10 bytes (your picture shows 11) and second, all of them are filled with '\0' (which calloc() does).

    How would I change [1] without defining the whole char? And then be able to define [2], and so on...

    By "change" if you mean assigning values then you can index them like:

    something[1] = 'a';
    something[5] = 'q';
    

    and so on.

    But do remember, using it as a C-string may not work (for example, printing something using printf("%s", something);) since there are intermediate zero bytes.