
Untitled
By: a guest on
Jul 29th, 2012 | syntax:
None | size: 2.14 KB | hits: 13 | expires: Never
concatanation char with char *
Ex:
char* foo ( char x, char * xc ) {
xc = realloc ( xc, 1 + strlen ( xc ) ) ;
strcat ( xc, x ) ;
return xc ;
}
p = heap variable
foo ( 'a', NULL ) ==> ------------
| 'a'| ' '|
------------
foo ( 'b', p ) ===> --------------------
| 'a' | 'b' | ' ' |
--------------------
foo ( 'c', p ) ===> --------------------------
| 'a' | 'b' | 'c' | ' ' |
--------------------------
size_t len = xc != NULL ? strlen(xc) : 0;
xc = realloc(xc, len + 1 + 1);
xc[len] = c;
xc[len + 1] = ' ';
len =strlen(xc);
xc = realloc ( xc, 2 + strlen ( xc ) ) ; //One for NULL character
sprintf(xc+len,"%c", x);
int len = 2;
if ( xc != NULL ) {
len += strlen( xc );
}
xc = realloc( xc, len );
*(xc+len-2) = x;
*(xc+len-1) = ' ';
char* append_char(char c, char * str)
{
char* new_str;
if(NULL != str) {
new_str = realloc(str, strlen(str) + 2);
strncpy(new_str, str, strlen(str));
new_str[strlen(str)] = c;
new_str[strlen(str)+1] = ' ';
} else {
new_str = malloc(2);
new_str[0] = c;
new_str[1] = ' ';
}
return new_str;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sl = 0; // sl for strlen(s), allocated memory size will be +1 byte
char* s = NULL;
char* ccat(char* s, char c) {
if (s == NULL) sl = 1; // allocating new memory
else sl = strlen(s) + 1; // +1 for new char
// realloc will work like malloc if s is NULL
s = realloc(s, sl+1); // +1 for zero at the end of string
if(s == NULL) {
fprintf(stderr, "realloc error");
exit(1);
}
s[sl-1] = c;
s[sl] = ' ';
return s;
}
int main(int argc, char** argv) {
s = ccat(s, 'Y');
printf("sl=%d s=%sn", sl, s);
s = ccat(s, 'P');
printf("sl=%d s=%sn", sl, s);
s = ccat(s, 'A');
printf("sl=%d s=%sn", sl, s);
if (s != NULL)
free(s);
exit(0);
}