简体   繁体   中英

C - Add char to beginnig of string

I try to create an array of string where each element is the concatenation of a char and a string.

For example:

char base_array[4] = {'A', 'C', 'G', 'T'};

char *kmer = "ACGT";

char *edge[4] = {"AACGT", "CACGT", "GACGT", "TACGT"};

I try with this code but generate segmentation fault.

char** kmer_head_append(const char *kmer, const char *base) {

    int i;
    char **edge = malloc(BASE * sizeof(char *));

    for ( i = 0; i < BASE; i++ ) {
        edge[i] = (char *) malloc((strlen(kmer) + 1) * sizeof(char *));
        strcpy(edge[i], &base[i]);
        *((*(edge + i)) + strlen(&base[i])) = kmer;
        *((*(edge + i)) + strlen(&base[i]) + 1) = '\0';
    }

    return edge;
}

int main(void) {

    char base_array[4] = {'A', 'C', 'G', 'T'};
    char **edge = kmer_head_append("ACGT", base_array);
    return 0;
}

EDIT:

If char *kmer = "DEFG" the output is an array where the element are ADEFG , CDEFG , GDEFG e TDEFG

You need size of char not char **

edge[i] =  malloc((strlen(kmer) + 2)); //2 to hold char + \0

Don't use strcpy if you want to copy single char .

    strcpy(edge[i], &base[i]); --> edge[i][0] = base[i];

You are doing pointer assignment what you need is strcpy

*((*(edge + i)) + strlen(&base[i])) = kmer; --> strcpy((char *)&edge[i][1], kmer);

Remove below line as \\0 is already appended by strcpy .

    *((*(edge + i)) + strlen(&base[i]) + 1) = '\0';

Or simply

   sprintf(edge[i], "%c%s", base[i], kmer);

You can use valgrind to see your where you segfault.

 char **edge = kmer_head_append("ACGT", base_array); //base_array is a char str[4]

So in your prototype you need to have:

char** kmer_head_append(const char *kmer,  char base[4])

You can malloc base like that:

char **edge = malloc(sizeof(char *) * (4 + 1)); because base is equal to 4 and + 1 for putting NULL at the end

Then:

for ( i = 0; i < 4 + 1; i++ ) {
        edge[i] = malloc(sizeof(char) * (5 + 1)) ; // 5 for the new string and + 1 for '\0'

Do step by step !

Then yo just have to do your line with strcpy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM