Echidna
Echidna

Reputation: 164

Appending chars into a String in C with a for loop

I'm still a newbie to C so please forgive me if anything below is wrong. I've searched this up online but nothing really helped.

Right now, I have the following code:

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

 void appendStr (char *str, char c)
  {
    for (;*str;str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;
  }

int main(){
    char string[] = "imtryingmybest";
    char result[] = "";
    
    for(int i = 0; i < strlen(string); i++){
        if(i >= 0 && i <= 3){
            appendStr(result, string[i]);
        }
    }
    printf("%s", result);
}

Basically, I'm trying to add the first 4 characters of the String named string to result with a for loop. My code above did not work. I've already tried to use strcat and strncat and neither of them worked for me either. When I used

strcat(result, string[i]);

It returns an error saying that the memory cannot be read.

I know that in this example it might have been easier if I just did

appendStr(result, string[0]);
appendStr(result, string[1]);
appendStr(result, string[2]);
appendStr(result, string[3]);

But there is a reason behind why I'm using a for loop that couldn't be explained in this example.

All in all, I'd appreciate it if someone could explain to me how to append individual characters to a string in a for loop.

Upvotes: 0

Views: 3544

Answers (4)

Jack Lilhammers
Jack Lilhammers

Reputation: 1247

As others have pointed out the code has a simple mistake in the allocation of the destination string.
When declaring an array without specifying its size, the compiler deduces it by its initializer, which in your case means a 0 + the NULL character.

char result[] = ""; // means { '\0' };

However, I think that the bigger issue here is that you're effectively coding a Schlemiel.
C strings have the serious drawback that they don't store their length, making functions that have to reach the end of the string linear in time complexity O(n).
You already know this, as shown by your function appendStr()

This isn't a serious issue until start you appending characters or strings in a loop.
In each iteration of your loop appendStr() reaches the last character of the string, and extends the string, making the next iteration a little slower.
In fact its time complexity is O(n²)
Of course this is not noticeable for small strings or loops with few iterations, but it'll become a problem if the data scales.

To avoid this you have to take into account the growing size of the string.
I modified appendStr() to show that now it starts from the last element of result

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

 void appendStr (char *str, char c, char *orig)
{
    printf("i: %ld\n", str - orig);
    for (; *str; str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;
}

int main()
{
    char string[32] = "imtryingmybest";
    char result[32] = "";
    
    for(int i = 0; i < strlen(string); i++) {
        if(i >= 0 && i <= 3) {
            // I'm passing a pointer to the last element of the string
            appendStr(&result[i], string[i], result);
        }
    }
    printf("%s", result);
}

You can run it here https://onlinegdb.com/HkogMxbG_

More on Schlemiel the painter
https://www.joelonsoftware.com/2001/12/11/back-to-basics/
https://codepen.io/JoshuaVB/pen/JzRoyp

Upvotes: 0

Kanony
Kanony

Reputation: 539

try to get rid of Magic numbers

#define BUFF_SIZE 10 // define some bytes to allocate in result char array
#define COPY_COUNT 4 // count of chars that will be copied 

int main(){
    char string[] = "imtryingmybest";
    char result[BUFF_SIZE] {}; // allocate some chunk of memory
    
    for(size_t i = 0; i < strlen(string); i++){
        if(i < COPY_COUNT){
            appendStr(result, string[i]);
        }
    }
    printf("%s", result);
}

I showed the solution code Paul Yang showed the problem

Upvotes: 0

Criss Hills
Criss Hills

Reputation: 189

The following code doesnt use your methods but successfully appends the first 4 chars to result

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

int main()
{
  // declare and initialize strings
  char str[] = "imtryingmybest";
  char result[5];    // the 5th slot is for \0 as all strings are null terminated

  // append chars to result
  strncat(result, str, 4);
//          ^      ^   ^
//          |      |   |- number of chars to be appended
//          |      | - string to be appended from
//          | - string to append to

  // print string
  printf("result: %s\n", result);

  return (0);
}

The result of the above is as wanted:

>> gcc -o test test.c
>> ./test
result: imtr

Let me know if anything is not clear so i can elaborate further

Upvotes: 1

Paul Yang
Paul Yang

Reputation: 346

string was ruined by the overflow of result buffer.

appendStr can be executed only once. next time strlen(string) will return 0. because *str++ = 0; has been written to the space of string.

result buffer has only 1 byte space, but you write 2 byte to it in appendStr call. the second byte will ruin string space.

I suggest debug with gdb.

Upvotes: 0

Related Questions