bug in function (?) and I don't understand - c

I have structure
typedef struct StructString {
void **string;
ringinfo RingInfo; // now i dont use it
} StructString;
I use it
StructString str;
now I try to give my str.string value with random
int n = 1 + rand() % 30;
printf("%d\n", n);
str.string = RandomInput(str.string, n);
printf("%s\n", *(char **)str.string);
printf("%d\n", strlen(str.string));
the RandomInput func is here
void **RandomInput(void **s, const int n) {
int i;
s = malloc((n+1) * sizeof(void *));
for (i = 0; i < n; ++i) {
char c=rand()%128;
printf("%c ", c);
s[i]=&c;
printf("%d ", i);
printf("%c\n", *(char *)s[i]);
}
s[n]='\n';
return s;
}
and I have two problems:
sometimes there is "" char (use the screenshot)
str.string not what it should be (we can understand what it should be using the screenshot)
help me please, I don't understand

As the printable ascii characters are ranged between 0x20 (whitespace)
and 0x7e (tilda), you can randomly pick one with rand() % ('~' - ' ' + 1) + ' ' or rand() % 95 + 32.
If you do not have a specific reason, it will be better to define
the data type of string as char *, not void **. Otherwise
the assigned sequence of characters may have gaps between characters.
You need to terminate the string s with a null character instead of
a newline.
Then the rewrited code will look like:
#include <stdio.h>
#include <stdlib.h>
typedef struct StructString {
char *string;
// ringinfo RingInfo; // now i dont use it
} StructString;
char *RandomInput(char *s, const int n)
{
int i;
s = malloc((n + 1) * sizeof(char)); // strictly we should check the return value
for (i = 0; i < n; ++i) {
char c = rand() % ('~' - ' ' + 1) + ' ';
// pick a printable character between ' ' and '~'
printf("%c ", c);
s[i] = c;
printf("%d ", i);
printf("%c\n", s[i]);
}
s[n] = '\0';
return s;
}
int main()
{
StructString str;
int n = 1 + rand() % 30;
printf("%d\n", n);
str.string = RandomInput(str.string, n);
printf("%s\n", str.string);
printf("%d\n", strlen(str.string));
return 0;
}

Related

Returning a whole array in C

Hi I am pretty new to C and was wondering how to return an entire array. For example I have this function here.
char* foo(int x)
{
char *num = (char*)malloc(x*sizeof(int));
num[0] = '1';
num[1] = '2';
num[2] = '3';
num[3] = '4';
return num;
}
I realized that when I return num it only returns the first index of num. But is there any way to return the whole array, 1234? Any help will be greatly appreciated!
Since the foo() function returns a pointer, you can see that all values are printed when you use the %s format specifier. The display() function prints the data in the memory area pointed to by the pointer as characters.
#include <stdio.h>
#include <stdlib.h>
char* foo(int x)
{
char* num = (char*) malloc((x + 1) * sizeof(char));
for(size_t i = 0 ; i < x ; ++i)
num[i] = i + 1 + '0';
num[x] = '\0';
return num;
}
void display(char *array, size_t size)
{
for(size_t i = 0 ; i < size && array[i] != '\0' ; ++i)
printf("array[%ld]: %c\n", i, array[i]);
}
int main()
{
const size_t size = 4;
char *result = foo(size);
printf("%s\n", result);
display(result, size);
return 0;
}
Output:
1234
array[0]: 1
array[1]: 2
array[2]: 3
array[3]: 4
See if you are new to C, then learn it first do some googling and research. If you don't find anything then read some theory of a similar topic for examples (How to return an array in C?). After that some error is happening in your code then you can ask it on stackoverflow.
By the way your should be like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *foo(int x); // fix prototype errors
char *foo(int x)
{
char *num = (char *)calloc(x + 1, sizeof(char)); // we added +1 to append the null terminating character in `num`
for (size_t i = 0; i < x; i++)
num[i] = (char)(i + 48);
return num;
}
/* #returns no. of character written on stdout */
int print_foo(const char *num); // fix prototype errors
int print_foo(const char *num)
{
if (num)
{
size_t z = 0;
for (size_t i = 0; i < num[i] != '\0'; i++)
z += fprintf(stdout, "num[%lu] = %c\n", i, num[i]);
return z;
}
return -1;
}
int main(void)
{
char *num = foo(10);
print_foo((const char *)num);
free(num); // free any heap allocated resources before exiting the application
return 0;
}

How to go through a array of strings using pointers alone

I'm trying to create a function that will receive an array of strings and the size and will return a string made of the biggest ASCII value's letter of each word, and the size of the string has to be precised and I'm not allowed using operator [](which is my main issue).
so for:
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
the function shall return a string with the word
"onor"
.
So i thought of creating a double for loop, first one will lead me into the location of each word in the array and the inside one will help me go through each word.
currently I'm having trouble finding the right format with my pointers to actually go through the letters of my first word.
I'm aware i haven't checked if my memory allocation is valid and also didn't free my memory yet as I'm trying to figure out whats wrong first.
char *bigLetters(char *str[], int size)
{
char *strNew = (char *)malloc((size + 1) * sizeof(char));
char max = 'a';
for (int i = 0; i < size; i++)
{
for (int j = 0; (*(str + i)+j) != NULL; j++)
{
if ((*(str + i) + j) >= max)
{
max = (*(str + i) + j);
}
}
*(strNew + i) = max;
}
*(strNew +(size+1)) = NULL;
return *(strNew);
}
void main()
{
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, SIZE);
printf("The new string is --> %s\n", res);
system("pause");
}
It will be easier to use the pointers if you separate the string pointer from its character pointer. Also, the max needs to be reset for each string, and you were writing the final string terminator outside of the memory allocated. You also use NULL where you should be using the character '\0'.
Finally the function was returning the first character of the new string (which I later free).
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
char *bigLetters(char *str[], int size)
{
char *strNew = malloc(size + 1); // no cast or sizeof necessary
for (int i = 0; i < size; i++)
{
char ch;
char max = 'a'; // moved inside loop
char *ptr = *(str + i); // use a separate pointer
for (int j = 0; (ch = *(ptr + j)) != '\0'; j++) // pull out the character
{
if (ch > max) // >= is not necessary
{
max = ch;
}
}
*(strNew + i) = max;
}
*(strNew + size) = '\0'; // correct the bounds error
return strNew; // just the pointer not its target
}
int main(void) // correct signature
{
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, SIZE);
printf("The new string is --> %s\n", res);
free(res); // clean up
system("pause");
}
Program output
The new string is --> onor
Press any key to continue . . .
If you didn't impose odd and unhelpful restrictions upon your coding, you'd be able to quickly see the problems with your code or even avoid making them in the first place. The problem is that the following statement makes no sense - you're comparing a char * with a char as you're only de-referencing str once.
if ((*(str + i) + j) >= max)
This is the same as writing
if ((str[i] + j) >= max)
which you can see the obvious mistake since what you're trying to write is the equivalent of
if ((str[i][j]) >= max)
which would be
if (*(*(str + i) + j) >= max)
Your compiler should be throwing up warnings because comparing between a pointer and an integer is rarely something you'd want to do.
You can use pointers as position indicators and advance them as needed.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
char
biggest_ascii(char* str)
{
char c = 0;
int i;
for (i = 0; *str; str++)
if (*str > c)
c = *str;
return c;
}
int
main()
{
int i;
char* strArr[SIZE] = {"hello", "and", "good", "morning"};
char** ppch;// current string
char res_str[SIZE + 1] = {0};/* resulting string,
initilized to 0 to be 0-terminated */
char* pch;// current char position
for (i = 0, ppch = strArr, pch = res_str; i < SIZE; i++, ppch++, pch++)
*pch = biggest_ascii(*ppch);
printf("%s\n", res_str);
return 0;
}
First, (*(str + i)+j) isn't the good way.
You could replace all
(*(str + i) + j)
by :
str[i][j]
Then, you need to reset the max to "a", because it's 'o' when you leave the loop, so your condition become str[i][j] >= o which is not what you want. Do it before the second for.
And I would have used while instead of for for the first loop.
I edited your code and this version is working fine for me :
#include <stdlib.h>
char *bigLetters(char *str[], int size)
{
char *strNew = (char *)malloc((size + 1) * sizeof(char));
int i = 0;
while (i < size) {
char max = 'a';
for (int j = 0; str[i][j]; j++) {
if (str[i][j] >= max) {
max = str[i][j];
}
}
strNew[i] = max;
i++;
}
strNew[i] = '\0';
return strNew;
}
void main()
{
char *strArr[5] = { "hello", "and", "good", "morning"};
char *res = bigLetters(strArr, 4);
printf("The new string is --> %s\n", res);
return 0;
}
str[i] is equivalent to *(str + i) and str[i][j] is equivalent to *(*(str + i) + j).
In your code you are using (*(str + i) + j) which is incorrect.
When char *[] passed to function, it will decay to char **. So, in bigLetters(), you can give char **str as the parameter. Also, it is inline with you requirement - not allowed using operator [].
Instead of hardcoding the dimension SIZE in char *strArr[SIZE], you can give the empty [] and let the compiler assign the dimension based on the size of initializer. In your case, size of initializer is 4 as you have given 4 strings in the strArr initializer. You can compute the size of strArr like this:
sizeof(strArr)/sizeof(strArr[0]);
You can do:
#include <stdio.h>
#include <stdlib.h>
char *bigLetters(char **str, size_t size) {
char *strNew = calloc(size + 1, 1); // sizeof(char) is always 1
// calloc will initialize all bytes in the allocated storage to zero.
// You dont need to add the null terminating character at the end of strNew
if (strNew == NULL)
exit(EXIT_FAILURE);
for (size_t i = 0; i < size; i++) {
for (size_t j = 0; *(*(str + i)+j) != '\0'; j++) {
if (*(*(str + i) + j) > *(strNew + i)) {
// You can directly fill the allocated memory with biggest ASCII
*(strNew + i) = *(*(str + i) + j);
}
}
}
return strNew;
}
int main(void) {
char *strArr[] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, sizeof(strArr)/sizeof(strArr[0]));
if (res != NULL) {
printf("The new string is --> %s\n", res);
free (res);
}
else
printf("bigLetters returned NULL\n");
return 0;
}
Note that void return type main() is not as per standard. Instead, you should use int as return type of main().

Converting Integer to dynamically allocated Char array, digit by digit using pointers

I need to convert Integer to Char, I can use only pointers without array indexes. Char array must be dynamically allocated. Can anybody review my code and tell my what am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
int main(){
int myNumber = 1234;
char *myString = (char*)malloc(2 * sizeof(char)); //memory for 1 char and '\0'
int i = 0; //parameter for tracking how far my pointer is from the beggining
if (myNumber < 0){
*myString = '-'; //if myNumber is negative put '-' in array
*myString = *(myString + 1); //move pointer to next position
i++;
}
while (myNumber != 0){
myString = (char*)realloc(myString, (i + 2) * sizeof(char)); //increse memory =+1
*myString = (myNumber % 10) + '0'; //put digit as char to array
myNumber /= 10;
*myString = *(myString + 1); //move pointer to next position
i++;
}
*myString = '\0'; //mark end of string
*myString = *(myString - i); //move pointer back to the beggining of string
printf("\n%s", *myString); // print char array (not working..)
return 0;
}
I know there are better ways of converting Int to String (sprintf), but my task is to do it that way.
In the code above I`m taking the digits from Int backwards, can it be done in correct order?
edit. as mentioned in the comments the part:
*myString = *(myString + 1);
is wrong, correct way of redirecting pointer by one space is:
myString++;
same with:
*myString = *(myString - i); //wrong
myString -=i; //ok
Edit2:
Now my code works! But I need to think how to correct the order of the digits.
#include <stdio.h>
#include <stdlib.h>
int main(){
int myNumber = 1234;
char *myString = (char*)malloc(2 * sizeof(char)); //memory for 1 char and '\0'
char * position = myString;
int i = 0;
if (myNumber < 0){
*position = '-'; //if myNumber is negative put '-' in array
position += i; //move pointer to next position
i++;
}
while (myNumber != 0){
myString = (char*)realloc(myString, ((i + 2) * sizeof(char))); //increse memory =+1
position = myString + i; // getting current position after reallocating
*position = (myNumber % 10) + '0'; //put digit to array
myNumber /= 10;
position++; //move pointer to next position
i++;
}
*position = '\0'; //mark end of string
char * temp = myString;
while (*temp != '\0'){
printf("%c", *temp); // print char array (not working..)
temp++;
}
return 0;
}
Edit 3 Problem solved, thanks for comments, I`m posting code in case anybody will look for similar solution.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// move each character in array one place to the right
// we need to make place for new character on the left
void moveArrayElementsRight(char *ptr, int len) {
for (int j = len; j > 1; j--) {
*(ptr + j - 1) = *(ptr + j - 2);
}
}
void intToStr(int myNumber, char* myString){
int i = 1; //track size of allocated memory
bool isMinus = false;
if (myNumber < 0) {
myNumber *= -1; //without this (myNumber % 10) + '0' wont work
isMinus = true;
}
if (myNumber == 0){ //special case for 0
myString = (char*)realloc(myString, ((i + 1) * sizeof(char)));
*myString = '0';
*(myString + 1) = '\0';
}
while (myNumber != 0) {
myString = (char*)realloc(myString, ((i + 1) * sizeof(char))); //increse memory =+1 for next digit
i++;
moveArrayElementsRight(myString, i);
*myString = (myNumber % 10) + '0'; //put digit to array
myNumber /= 10;
}
if (isMinus) {
myString = (char*)realloc(myString, ((i + 1) * sizeof(char))); //increse memory =+1 for '-' sign
i++;
moveArrayElementsRight(myString, i);
*myString = '-'; //put sign at the beginning
}
}
int main() {
int numberToConvert = -10;
char *numberAsString = (char*)malloc(sizeof(char)); //create empty array, with place only for '\0'
*numberAsString = '\0'; //mark the end of array
intToStr(numberToConvert, numberAsString);
printf("%s", numberAsString);
return 0;
}
SPOILER: Don't read or copy this if you don't want the solution.
The following is an example of implementation, using recursive:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <string.h>
#include <time.h>
#include <errno.h>
static size_t int_to_str_size(int n, size_t acc, int base_size) {
int next = n / base_size;
if (next != 0) {
return int_to_str_size(next, acc + 1, base_size);
} else {
return n < 0 ? acc + 2 : acc + 1;
}
}
static void int_to_str_write(int n, char *str, char *base, int base_size) {
*str = base[abs(n % base_size)];
int next = n / base_size;
if (next != 0) {
int_to_str_write(next, str - 1, base, base_size);
} else {
if (n < 0) {
*(str - 1) = '-';
}
}
}
static char *int_to_str(int n, char *base) {
size_t base_size = strlen(base);
if (base_size < 2 || base_size > INT_MAX) {
errno = EINVAL;
return NULL;
}
size_t size = int_to_str_size(n, 0, (int)base_size);
char *str = malloc(size + 1);
if (str == NULL) {
return NULL;
}
str[size] = '\0';
int_to_str_write(n, str + size - 1, base, (int)base_size);
return str;
}
int main(void) {
srand((unsigned int)time(NULL));
for (uintmax_t i = 0; i < 42; i++) {
int n = rand() % 2 ? rand() : -rand();
char *str = int_to_str(n, "0123456789");
if (str != NULL) {
printf("%d == %s\n", n, str);
free(str);
} else {
perror("int_to_str()");
}
}
}

Hex/Dec Program in C getting the wrong output and cant use Scanf

Whenever I run my program, I think that I am getting the wrong output using the included test strings, though I think my first function is working. Tthe files I have are xbits.c xbits.h and two versions of showxbits.c, one that is instructor provided and the other is the one I am trying to use scanf with. The program is supposed to convert an integer to a hex string and then a hex string to an integer. My main problem is, while I think that my code works with the instructor test input, I know it doesn't work with the scanf showxbits because it gives answers such as 0xS when 127 is inputed.
Here is the xbits.c
#include <stdio.h>
#include <math.h>
int hex_To_dec(int c) {
char hex_values[] = "aAbBcCdDeEfF";
int i;
int answer = 0;
for (i=0; answer == 0 && hex_values[i] != '\0'; i++) {
if (hex_values[i] == c) {
answer = 10 + (i/2);
}
}
return answer;
}
/* function represents the int n as a hexstring which it places in the
hexstring array */
void itox(char* s, int n)
{
char *digits = "0123456789ABCDEF";
int i=0,j;
char temp;
while(n > 0)
{
s[i] = digits[n % 16];
n /= 16;
i++;
}
s[i] = '\0'; // Add null terminator
i--;
// Now reverse it in place
for(j=0; j < i / 2; j++)
{
temp = s[j];
s[j] = s[i - j];
s[i - j] = temp;
}
}
/* function converts hexstring array to equivalent integer value */
int xtoi(char hexstring[]) {
//printf("in xtoi, processing %s\n", hexstring);
int answer = 0;
int i = 0;
int valid = 1;
int hexit;
if (hexstring[i] == '0') {
++i;
if (hexstring[i] == 'x' || hexstring[i] == 'X') {
++i;
}
}
while(valid && hexstring[i] != '\0') {
answer = answer * 16;
if(hexstring[i] >='0' && hexstring[i] <= '9') {
answer = answer + (hexstring[i] - '0');
}
else {
hexit = hex_To_dec(hexstring[i]);
if (hexit == 0) {
valid = 0;
}
else {
answer = answer + hexit;
}
}
++i;
}
if(!valid) {
answer = 0;
}
return answer;
}
Here is the showxbits.c provided by the instructor:
/*
* stub driver for functions to study integer-hex conversions
*
*/
#include <stdio.h>
#include <string.h>
#include "xbits.h"
#define ENOUGH_SPACE 1000 /* not really enough space */
int main() {
char hexstring[ENOUGH_SPACE];
int m=0, n = 0x79FEB220;
itox(hexstring, n);
/* for stub testing: create a fake input string */
strcpy(hexstring, "6BCD7890");
m = xtoi(hexstring);
printf("\t%12d %s %12d\n", n, hexstring, m);
return 0; /* everything is just fine */
}
And here is the showxbits that has scanf in it:
/*
* stub driver for functions to study integer-hex conversions
*
*/
#include <stdio.h>
#include <string.h>
#include "xbits.h"
#define ENOUGH_SPACE 100 /* not really enough space */
int main() {
char hexstring[ENOUGH_SPACE];
//int m=0, n = 0x79FEB220;
int n, m;
while ((scanf("%d", &n)) == 1) {
itox(hexstring, n);
m = xtoi( hexstring);
printf("%12d %s %12d\n", n, hexstring, m);
}
return 0; /* everything is just fine */
}
Like I said, I am getting weird outputs when using the scanf function. I am a complete beginner programmer and would really appreciate any help that can be offered. Thanks!
Because there is a mistake in the function itox , which would cause the wrong result when reverse string. Then, the wrong hexstring from itox will result in the abnormal output finally.
The quick fix is to replace j < i / 2 with j < i / 2 + 1
void itox(char* s, int n)
{
//......
// Now reverse it in place
for(j=0; j < i / 2 + 1 ; j++)
{
temp = s[j];
s[j] = s[i - j];
s[i - j] = temp;
}
}
You don't need to reverse the string to convert to hex ascii:
#include <stdio.h>
const char* hexlat="0123456789ABCDEF";
char *binaryToHex(unsigned int answer, char *result){
if(answer==0) return result;
else{
result=binaryToHex(answer>>4,result);
*result=hexlat[answer & 0x0F];
return result+1;
}
};
int main(void) {
unsigned int answer=0x12340ADF;
char hexAnswer[32];
*binaryToHex(answer,hexAnswer)='\0';
printf("%s",hexAnswer);
return 0;
}

Replace char in string with another string in C

I'm trying to replace ' ' (space) with '___' (triple underscore) in C.
Here is my code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *a = "12 34 56";
int a_l = strlen(a);
printf("str1: \"%s\" (%d)\n", a, a_l);
char *b = "___";
int b_l = strlen(b);
printf("str2: \"%s\" (%d)\n", b, b_l);
for (int i = 0; i < a_l; i++) {
if (a[i] == ' ') {
char *o = malloc(a_l + b_l);
strncpy(o, a, i);
strncpy(o + i, b, a_l);
//strncpy help
printf("out: \"%s\"\n", o);
}
}
return 0;
}
I think that it is right so far, but I need to replace the comment line with correct strncpy (take the rest of string a (excluding space) and append it to string o). So the output should be like this:
str1: "12 34 56" (8)
str2: "___" (3)
out: "12___34 56"
out: "12 34___56"
If there are other mistakes in my code, please tell me.
UPD: This shouldn't replace all spaces in a loop. If the source string contains 8 spaces, there should be 8 lines printed and in each line only one space should be replaced.
You are overcomplicating this so much that I just TL;DR.
Some remarks that you might surely want to read, learn, embrace well and use:
I. int is not for string lengths and stuff. size_t is for string lengths and stuff.
II. String literals cannot be modified, so using the legacy char * type for assigning them to a variable is no good by any means, const-qualify that poor pointer base type.
III. Use VLAs instead of malloc() if dynamic memory management is not really needed (we're not living in 1989 anymore).
IV. NUL-terminate your strings because C stdlib routines expect you to do so.
int main()
{
const char *in = "foo bar baz";
int nspc = 0;
for (const char *p = strchr(in, ' '); p; p = strchr(p + 1, ' '))
nspc++;
char buf[strlen(in) + nspc * 2 + 1];
memset(buf, 0, sizeof(buf));
const char *s = in;
for (const char *p = strchr(s, ' '); p; p = strchr(s, ' ')) {
strncat(buf, s, p - s);
strcat(buf, "___");
s = p + 1;
}
const char *end = in + strlen(in);
strncat(buf, s, end - s);
printf("%s\n", buf);
return 0;
}
You can try this one. The problem comes from the fact that a_l + b_l in your malloc is always the same value. It doesn't affect by number of spaces.
int count = 0, index = 0;
for (int i = 0; i < a_l; ++i) {
if (a[i] == ' ') {
count++;
}
}
const char *o = malloc(a_l + 2 * count + 1); // 2 is because you add 3 new symbols, but remove 1 so 3 - 1 = 2
memset(o, 0, sizeof(o));
for (int i = 0; i < a_l; ++i) {
if (a[i] != ' ')
o[index++] = a[i];
else {
o[index++] = '_';
o[index++] = '_';
o[index++] = '_';
}
}
Without using library function!!!
while(*string)
{
if(*string=='\\')
{
*string++;
while(repl_len--)
*dest++ = *repl_string++;
}
else
{
*dest++ = *string++;
}
repl_string = temp_repl_string;
repl_len = temp_repl_len;
}
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
size_t my_strlen(const char *str, size_t *spc){
size_t len;
*spc = len = 0;
while(*str){
++len;
if(*str++ == ' ')++*spc;
}
return len;
}
int main(void){
char *a = "12 34 56";
size_t spc;
int a_l = my_strlen(a, &spc);
printf("str1: \"%s\" (%d)\n", a, a_l);
char *b = "___";
int b_l = strlen(b);
printf("str2: \"%s\" (%d)\n", b, b_l);
char *p, *o = malloc(a_l - spc + spc * b_l + 1);
p=o;
for (int i = 0; i < a_l; i++) {
if(a[i] == ' ') {
strncpy(p, b, b_l);
p += b_l;
} else {
*p++ = a[i];
}
}
*p = '\0';
printf("out: \"%s\"\n", o);
free(o);
return 0;
}
I see that many answers have been added, but this may have been done very simply with a single loop. Since the string is very short, you can sacrifice memory over CPU and allocate an array 3 times +1 bigger than the original string, and be sure that it won't be overflowed:
const char* string= "12 34 56";
size_t length= strlen(string);
char result[length*3 +1];
unsigned int index= 0;
memset(result, '\0', length*3+1);
for(int i=0; i<length; i++)
{
if(string[i]!= ' ')
{
result[index++]= string[i];
}
else
{
strcat(result,"___");
index+= 3;
}
}
I found another thread and after reading the answers, I figured out that the right line should look like this:
strncpy(o + i + b_l, a + i + 1, a_l - i);
And after few fixes that were suggested in this thread my code looks like this:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *a = "12 34 56";
size_t a_l = strlen(a);
printf("str1: \"%s\" (%d)\n", a, a_l);
char *b = "___";
size_t b_l = strlen(b);
printf("str2: \"%s\" (%d)\n", b, b_l);
for (int i = 0; i < a_l; i++) {
if (a[i] == ' ') {
char *o = malloc(a_l + b_l);
strncpy(o, a, i);
strcpy(o + i, b);
strncpy(o + i + b_l, a + i + 1, a_l - i);
printf("out: \"%s\"\n", o);
free(o);
}
}
return 0;
}
And this prints the desired putput.

Resources