This code is driving me up the wall. The goal is to split to char[] based on a comma. It works in java. But prints weird output in C. The error I suspect is at 28 on the second iteration of the loop where I tried to add 5 the array turns into weird characters.
#include <stdio.h>
#include <string.h>
main()
{
char asshat[] = {'4','5','5',',','7','4','7','\0'};
int firstSize = 0;//
int secondSize = 0;//
//new = 4 \0 \0
char first[] = {'0', '\0'};//
//new =
char second[] = {'0', '\0'};//
char *first_ptr = first;
char *second_ptr = second;
int takingFirst = 1;
int takingSecond = 0;
int i;
for (i = 0; i < strlen(asshat); i++)
{
if (asshat[i] != ',')
{
if (takingFirst == 1)
{
first_ptr[firstSize] = asshat[i];//ERROR here when you add 5 you s**t bricks
firstSize++;
if (asshat[i+1] != ',')
{
char new[firstSize+2];
int k;
for (k = 0; k < strlen(first_ptr); k++)
{
new[k] = first_ptr[k];
}
new[firstSize] = '0';
new[firstSize+1] = '\0';
first_ptr = new;
}
}
if (takingSecond == 1)
{
second_ptr[secondSize] = asshat[i];
secondSize++;
if (asshat[i+1] != '\0')
{
char new[secondSize+2];
int k;
for (k = 0; k < strlen(second_ptr); k++)
{
new[k] = second_ptr[k];
}
new[secondSize+1] = '\0';
second_ptr = new;
}
}
}
else
{
takingFirst = 0;
takingSecond = 1;
}
}
printf("%d\n",strlen(first_ptr));
printf("%c%c%c\n",first_ptr[0],first_ptr[1],first_ptr[2]);
printf("%s\n",first_ptr);
printf("%d\n",strlen(second_ptr));
printf("%c%c%c\n",second_ptr[0],second_ptr[1],second_ptr[2]);
printf("%s\n",second_ptr);
}
It’s very hard to read what your solution is doing. I tried reimplementing it to be simpler while maintaining your pointer play:
This produces: