简体   繁体   中英

How can I add a char on the begining of a string in C?

I'm trying to put a char on the begining of a string but when I print the final string the result is:

Process finished with exit code -1073741819 (0xC0000005)

This is my code:

char * letter=malloc(strlen(output)+2);
letter[0]='a';
strcat(letter,output);
output=malloc(strlen(output)+2);
strcpy(output,letter);
free(letter);
printf("\n%s",output);

output is string input that i give to the method.

To use strcat the destination array shall contain a string. Your array letter does not contain a string.

You could write for example

letter[0] = 'a';
letter[1] = '\0';
strcat( letter, output );

or just

letter[0] = 'a';
strcpy( letter + 1, output );

Pay attention to that it seems this statement

output=malloc(strlen(output)+2);

produces a memory leak because the previously allocated memory pointed to by the pointer output was not freed.

The task could be done without allocating a memory for an auxiliary array. You could use the standard function realloc to reallocate the original array pointed to by output . And then move the stored string using memmove to the right one position and then insert the character 'a' in the first position.

Here is a demonstrative program.

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

int main(void) 
{
    size_t n = 5;
    char *s = malloc( n * sizeof( char ) );
    strcpy( s, "ello" );
    
    char *tmp = realloc( s, ( n + 1 ) * sizeof( char ) );
    
    if ( tmp != NULL )
    {
        s = tmp;
        memmove( s + 1, s, n );
        s[0] = 'H';
        ++n;
    }
    
    puts( s );
    
    free( s );
    
    return 0;
}

The program output is

Hello

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