1

I'm trying to append a char to string.

I tried

char *string = malloc(strlen(text) * sizeof (char));
for(i=0, i <n; i++)
{
    j = i;
    while (j <= strlen(text))
    {
        string[strlen(string)] = text[i];
        j = j + n;
    }
    string[strlen(string)] = '\0';
    printf("%s", string);
    string = "";
}

My goal is creating variations of text.I got segmentation fault with this code. What am i doing wrong?

EDIT: to be more clear what i want to do is: lets say text = "asdfghjk" And for n = 3 i want the following output:

afj
sgk
dh
6
  • Can you explain what you are trying to achieve ? Commented Oct 21, 2011 at 18:42
  • Here is a hint: strlen is not an O(1) operation. It recomputes the string length (based on finding the trailing '\0') every time you call it. It's generally better to call it once and store that in a variable, updating the variable if you add to the string, than to call it three times. Commented Oct 21, 2011 at 18:42
  • 1
    You can't strlen(string) when the null terminator has not been set to string. This will produce segmentation fault. Commented Oct 21, 2011 at 18:44
  • I can't get logic of your code to be honest. For text="teststring" and n=3 (assuming all errors are fixed) you will get string="tttteeesss". I don't see any reason you would want to do it. Commented Oct 21, 2011 at 18:54
  • okay, your update shows a really different requirement that and what you are attempting to describe Forest which was trying to put a character at the end of this string, here you are simply asking how to split a string into n segments, all delimited by the newline (\n) character. Two different problems... I am going to post solutions to both. Commented Oct 21, 2011 at 19:30

5 Answers 5

2

I would do something like:

char *AppendCharToString( const char *orig, char newChar )
{
   int oldLength = strlen(orig);
   char *result = malloc( oldLength+2 ); // one byte for the new char, one for the terminator
   strcpy(result, orig);
   result[oldLength] = newChar;
   result[oldLength+1] = 0;
   return result;
}
Sign up to request clarification or add additional context in comments.

4 Comments

If your strings are > the size of an integer, I wouldn't recommend this method. :-) (Of course you are right, but I'm old-school sometimes)
True. I'm interested in what you would recommend for strings that large, though.
You should use a size_t instead of an int.
For small additions, you could allocate your strings with some extra space at the end where you could store appended data. For larger additions, you could keep an array of memory buffers. C++ has std::deque for that sort of thing. You could mimic it even in plain C if you wanted to. A linked list of strings could work too. It really depends on if you need the strings to be contiguous.
1

This is what you want.

// Params
char *text = "asdfghjk";
int n = 3;
// Code
int i, j, k, len = strlen(text);
char *s = malloc((len + 1) * sizeof (char));
for (i = 0, i < n; i++) {
    for (j = i, k = 0; j < len; j += n) s[k++] = text[j];
    s[k] = 0;
}
printf("%s\n", s);

First of all, a string with terminating zero will take strlen()+1 bytes of space. Not just strlen(). Second, don't ever use strlen() in a loop. Precalculate it in int and use it. Third, you had an error: you had text[i], but meant text[j]. Fourth, as authors of previous answers mentioned, you can not calculate a length of a string if it does not have terminating zero yet. Fifth, you don't need to clear a string after each iteration since overwriting its characters and adding new terminating zero will make it completely new string.

Comments

0

you should just create a new String, appending to it what you want, at the bottom where ` string[strlen(string)] = '\0'; printf("%s", string); string = new String("");

`

Comments

0
string[strlen(string)] = '\0';

This won't work as expected. string won't be NULL-terminated so strlen() will look behind the end of the string for the \0 and won't find it. (and if it did you would overwrite \0 with \0). What you want is strlen(text) there. And then

char *string = malloc(strlen(text) + 1);

To have enough space.

Comments

0

Okay answer to problem as it was stated originally how to append a single character to the end of a string which DOES NOT have space allocated for it.

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

/* note that str can be NULL for a new string */
char *straddchr(char *str, int c) {
    size_t len = str ? 2+strlen(str) : 2;
    char *p = realloc(str, len); /* add space (need space for char and \0) */
    if ( !p ) 
        return str;
    str = p;
    str[len-2] = c; 
    str[len-1] = 0;
    return str;
}

int main() {
    char *str = NULL;
    str = malloc(5);
    strcpy(str, "Hell");
    str = straddchr(str, 'o');
    str = straddchr(str, ' ');
    str = straddchr(str, 'w');
    str = straddchr(str, 'o');
    str = straddchr(str, 'r');
    str = straddchr(str, 'l');
    str = straddchr(str, 'd');
    printf("%s\n", str);
}

And here is the second bit which inserts a character every 'n'th position

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

/* note that str can be NULL for a new string */
char *strinjectchr(char *str, int c, int n) {
    size_t len = str ? strlen(str) + n + 1: n + 1;
    str = realloc(str, len);
    char *p;
    int i;

    if ( len == 1+n ) { /* original string was NULL */
    str[n] = 0;
    return memset(str, c, len-1); /* just use memset and send it all back */
    }

    char *copy = strdup(str);
    for (i = 0, p = copy; *p != 0; p++) {
        str[i++] = *p;
        if ( (i > 0) && ((1+(p - copy))%n == 0) ) {
             str[i] = c;
             i++;
    }
    }
    str[len] = 0;
    free(copy);
    return str;
}

int main() {
    char *str = NULL;
    str = strinjectchr(str, 'X', 25);
    printf("str is: %s\n", str);
    str = strinjectchr(str, '-', 5);
    printf("str is: %s\n", str);
    str = strdup("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    str = strinjectchr(str, '\n', 3);
    printf("str is: %s\n", str);
}

1 Comment

The indentations are a bit off in the code, but you can fix those in an editor this is a bit painful here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.