Brain**** implementation in C - c

I'm trying to run a hello world program with the brainfuck implementation that I made this week but I'm getting a strange output.
This is the hello world file that I'm trying to run.
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.-------
-.>>+.>++.
I have saved it to hello.txt, and am parsing it in the main function of the program.
The output is
1 -3 4 4 7 0 -1 7 10 4 -4 1 2
which, when you add 72, and convert to character , gives
I E L L O H G O R L D I J
So it seems like there is something I'm missing, even though its sort of close to the right solution.
But I'll go into the structure of the thing anyhow, the general idea is as followed:
We have two 'tapes', a program to follow which I label 'parsed' which has a pointer 'attached' to it, and an empty tape to write into, which I label 'mem', which also has a pointer 'attached' to it. We also have a list of structures that we can use to jump between bracket locations.
In the main function, there are three parts: first I parse the program and store it in an array. Then I run through this parsing and match brackets, then I start the brainfuck loop and write the output onto the empty array, until the final character has been reached.
In the brainfuck loop, when we find a bracket, we run through the list of pairs to find its match, and then jump to that location.
Maybe it's a bit clunky, but I hope it makes sense.
#include <stdio.h>
#include <stdlib.h>
#define MAX 30000
//input tape
char parsed[MAX];
char * ptr;
//bracket matching
struct bracketlinks{
char * bracket_1;
char * bracket_2;
};
struct bracketlinks * pairslist;
int bracket_count;
//output tape
char mem[MAX] = {0};
int * mptr;
int main(){
mptr = malloc(sizeof(int));
//parse text file and make list of tokens
FILE * parsecode;
parsecode = fopen("helloworldbf.txt", "r");
int count = 0;
char buffer;
while(!feof(parsecode)){
buffer = fgetc(parsecode);
if(buffer == 10){break;}
if(buffer == 32){continue;}
else{
parsed[count] = buffer;
if(buffer == 91 || buffer == 93){
bracket_count++;
}
count++;
}
}
fclose(parsecode);
pairslist = malloc(bracket_count * sizeof(char*));
//creates array of structures which match brackets so we can perform memory jumps
int reset_count;
int list_counter = 0;
for(int i = 0; i < count; i++){
if(parsed[i] == '['){
reset_count = 0;
for(int j = 0; j < count - i + 1; j++){
if(parsed[i + j] == '['){reset_count++;}
if(parsed[i + j] == ']'){reset_count--;}
if(reset_count == 0){
struct bracketlinks new;
new.bracket_1 = &parsed[i];
new.bracket_2 = &parsed[i + j];
pairslist[list_counter] = new;
list_counter++;
break;
}
else{continue;}
}
}
else{continue;}
}
//runs through the input tape and performs operations on the output tape
ptr = parsed;
char final_token = ptr[count];
while(ptr[0] != final_token){
if(ptr[0] == '['){
if(mem[mptr[0]]){++ptr;}
if(!mem[mptr[0]]){
for(int i = 0; i < bracket_count/2; i++){
if(pairslist[i].bracket_1 == &ptr[0]){
ptr = ++pairslist[i].bracket_2;
}
if(pairslist[i].bracket_2 == &ptr[0]){
ptr = ++pairslist[i].bracket_1;
}
else{continue;}
}
}
}
if(ptr[0] == ']'){
if(!mem[mptr[0]]){
for(int i = 0; i < bracket_count/2; i++){
if(pairslist[i].bracket_1 == &ptr[0]){
ptr = ++pairslist[i].bracket_2;
}
if(pairslist[i].bracket_2 == &ptr[0]){
ptr = ++pairslist[i].bracket_1;
}
else{continue;}
}
}
if(mem[mptr[0]]){++ptr;}
else{continue;}
}
if(ptr[0] == '+'){++ptr;++mem[mptr[0]];}
if(ptr[0] == '-'){++ptr;--mem[mptr[0]];}
if(ptr[0] == '>'){++ptr; mptr[0]++;}
if(ptr[0] == '<'){mptr[0]--;++ptr;}
if(ptr[0] == '.'){++ptr; printf("%c %d \n", mem[mptr[0]] + 72, mem[mptr[0]]);}
else{continue;}
}
free(pairslist);
free(mptr);
return 0;
}
Any help would be massively appreciated,
Cheers..

OK so here's the fix for the main bug: basically just switch the exclamation marks and don't be a numpty.
if(ptr[0] == ']'){
if(mem[mptr[0]]){
for(int i = 0; i < bracket_count/2; i++){
if(pairslist[i].bracket_1 == &ptr[0]){
ptr = ++pairslist[i].bracket_2;
}
if(pairslist[i].bracket_2 == &ptr[0]){
ptr = ++pairslist[i].bracket_1;
}
else{continue;}
}
}
if(!mem[mptr[0]]){++ptr;}
else{continue;}
}
Still working on the !feof thing but will update with that too

Related

Input in specific format (matrix)

I have an issue with input in my homework. On stdin, I will get a specifically formatted input.
In first line, there will be 2 integers, that determine the size of a matrix (rows and cols). All the lines after represent rows of the matrix.
I essentially want to do something like getline(), but I don't want to use getline(). In fact I can't, its forbidden in the homework. Therefore I have to scan int by int (or char by char I guess). The issue here is I need it to be bulletproof (almost). Dummy-proof at least.
I'm imagining a big while loop that keeps going until EOF and inside that another loop (perhaps?) which always reads a line, saves it to my allocated matrix and carries on to the next. I'm aware that I'm supposed to be checking for '\n', but I kind of lack the ability to think of a solution today.
Here's what I'm working with: My matrices are a structure.
struct Matrix{
int nrows;
int ncols;
int** matrix;
};
I then have multiple functions.
A function to dynamically allocate space for the matrix of specific size:
struct Matrix init_matrix(int r, int c)
{
struct Matrix mat;
mat.nrows = r;
mat.ncols = c;
mat.matrix = calloc(r, sizeof(int *));
for(int i = 0; i < r; ++i)
{
*(mat.matrix+i) = calloc(c, sizeof(int));
}
return mat;
}
A function to free the previously allocated space:
void free_matrix(struct Matrix mat)
{
int top = mat.nrows;
for(int i = 0; i < top; ++i)
{
free(mat.matrix[i]);
}
free(mat.matrix);
}
Those 2 functions work perfectly fine.
Now I'm trying to make a function create_matrix(void) (at least I think it shouldn't take any args), that will read the input I'm supposed to receive, for example:
3 3
1 2 3
4 5 6
7 8 9
when the function reads the input, it could tell if the input is incorrect or is in incorrect format and exit the program with corresponding exit value (like 100 f.e.) If the input is correct and in correct format, it calls init_matrix() and then saves input to the matrix.
For your deeper understanding: the whole input I'm supposed to receive is:
matrix A (like above, size in first line, values in lines after)
an operation (+,-,*)
matrix B
Then execute the operation (A*B, A+B etc.). I'm trying to make most things into functions, so the main would be very simple, f.e.
int main(int argc, char *argv[])
{
struct Matrix mat1 = create_matrix();
char operation = get_operation();
struct Matrix mat2 = create_matrix();
struct Matrix result = compute(mat1,mat2, operation);
return 0;
}
Something in those lines, if you get me. The thing is I want to make the program complex enough so that I could later edit it to handle a bigger sequence (up to 100) of matrices than just two. Right now I could do it the dirty way, make it work for two matrices with one operation, but that's not what I really want.
Well, here's how I solved it. It works. It's not anywhere close to perfect, but it works, upload system took it and gave it full amount of points, so I'm satisfied.
struct Matrix read_matrix(FILE *fp)
{
struct Matrix mat;
//FIRST LINE
int ch;
int i = 0;
int n = 20;
char* line = calloc(n,sizeof(char));
while((ch = fgetc(fp)) != EOF && ch != '\n')
{
*(line + i++) = ch;
}
*(line + n-1) = '\0';
int r,c;
int k = sscanf(line,"%d %d", &r, &c);
if(k != 2)
{
fprintf(stderr, "Error: Chybny vstup!\n");
exit(100);
}
free(line);
//MATRIX
line = calloc(c, sizeof(int));
mat = init_matrix(r, c);
i = 0;
r = 0;
while(r < mat.nrows && (ch = fgetc(fp)))
{
if(ch == '\n' || ch == EOF)
{
*(line + i) = '\0';
int offset;
char *data = line;
for(int j = 0; j < mat.ncols; ++j)
{
int d = sscanf(data, " %d%n", &mat.matrix[r][j], &offset);
if(d != 1){
fprintf(stderr, "Error: Chybny vstup!\n");
exit(100);
}
data += offset;
}
i = 0;
++r;
if(ch == EOF){
break;
}
} else
{
*(line + i++) = ch;
}
}
free(line);
return mat;
}

C - reading multiple file streams

Im writing my own simplified version of the classic UNIX program 'wc' (word count). It counts number of lines, words, and characters. All these features work fine. But where i run into trouble is when im trying to read multiple files from *argv[x]. I need to make every variable into an array, and run the whole process through loops to achieve what im looking for.
My program returns a segmentation fault. Something is not being assigned into the arrays at some point in the code, and i can't seem to figure out exactly where that is.
Any help is much appreciated :)
/*
* [PROGRAM] wc (word count)
* [AUTHOR] Jesper M. Olsen # jm0.codes
* [DATE] September 9th 2015
* [PURPOSE] Returns number of lines, words, and characters in a file
*
* [DESCRIPTION] This program is meant to be utilized as a handy little browsing tool.
* For instance, while moving through the filesystem of a programming archive,
* just type 'wc <filename>' and you will get number of lines, words and characters returned promptly.
*/
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc == 1)
return -1;
int numL[argc]; /* initialize array value placeholders */
int numW[argc];
int numC[argc];
int getC[argc];
int getW[argc];
int setNull;
for (setNull = 1; setNull <= argc-1; setNull++) { /* assign ZERO to value placeholders */
numL[setNull] = 0;
numW[setNull] = 0;
numC[setNull] = 0;
getW[setNull] = 0;
}
int x;
FILE *fOp[argc-1];
for (x = 1; x <= argc-1; x++) { /* open file stream for each file */
fOp[x] = fopen(argv[x], "r");
if (fOp[x] == NULL)
return -1;
}
int y;
for (y = 1; (getC[y] = getc(fOp[y])) != EOF; y++) {
if (getC[y] == '\n') numL[y]++;
if (getC[y] == ' ' || getC[y] == '\n' || getC[y] == '\t') getW[y] = 0;
else if (getW[y] == 0) {
getW[y] = 1;
numW[y]++;
} numC[y]++;
}
int z;
for (z = 1; z <= argc-1; z++) { /* close files */
fclose(fOp[z]);
}
int c;
for (c = 1; c <= argc-1; c++) {
printf("[%s] %dL %dW %dC\n", argv[c], numL[c], numW[c], numC[c]);
}
return 0;
}
This will cause a segfault when you reach the last file
FILE *fOp[argc-1];
for (x = 1; x <= argc-1; x++) { /* open file stream for each file */
fOp[x] = fopen(argv[x], "r");
if (fOp[x] == NULL)
return -1;
}
because the array is not large enough. It should be
FILE *fOp[argc];
The mistake would be easier to see if you used
< argc
instead of
<= argc-1
in your loops.
I think problem may be
here -
for (y = 1; (getC[y] = getc(fOp[y])) != EOF; y++) {
if (getC[y] == '\n') numL[y]++;
if (getC[y] == ' ' || getC[y] == '\n' || getC[y] == '\t') getW[y] = 0;
else if (getW[y] == 0) {
getW[y] = 1;
numW[y]++;
} numC[y]++;
}
As arrays can argc number of elements but with this loop you may have read and stored integers more than argc in getC . Thus getting Seg Fault .
But we don't know what it inside files we can't be sure.
Try increasing size of arrays .
Note - It is better to initialize array starting with index 0. In this code you haven't use index 0.

Calculator in C using stack

I'm trying to create a calculator in c, which can calculate with priority and get right results for examples like these:
((5+5)/3)*3) -- > 9
((1+2) * 3) -- > 9
These examples my code below can calculate. But for something like this
(2+5) * (2+5), my program gives wrong answer.
I'm using 2 stacks. One for operators and one for numbers. It works on this principle:
follows:
((4 - 2) * 5) + 3 --> normal infix expression:
+ * - 4 2 5 3
Pseudo code:
Read + (an operation), push it onto the stack,
Read * (an operation), push it onto the stack,
Read - (an operation), push it onto the stack,
Read 4 (a number), the top of the stack is not a number, so push it onto the stack.
Read 2 (a number), the top of the stack is a number, so pop from the stack twice, you get 4 - 2, calculate it (2), and push the result (2) onto the stack.
Read 5 (a number), the top of the stack is a number, so pop from the stack twice, you get 2 * 5, push the result (10) onto the stack.
Read 3 (a number), the top of the stack is a number, so pop from the stack twice, you get 3 + 10, push the result (13) onto the stack.
Nothing left to read, pop from the stack and return the result (13).
Actual code:
#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 102
typedef struct
{
char stk[MAXSIZE];
int top;
}STACK;
typedef struct stack
{
int stk[MAXSIZE];
int itop;
}INT_STACK;
STACK s;
INT_STACK a;
void push(char);
char pop(void);
void display(void);
int main()
{
a.itop = 0;
char string[MAXSIZE],vyb,vyb2;
int cislo1,cislo2,vysledok;
while (gets(string) != NULL){
for(int j = strlen(string); j > 0; j--){
if(string[j] == '*' || string[j] == '/' || string[j] == '+' || string[j] == '-')
push(string[j]);
}
//display();
for(int j = 0; j < strlen(string); j++){
if(isdigit(string[j])&&!(a.itop)){
//display();
char pomoc[2];
pomoc[0] = string[j];
pomoc[1] = '\0';
int_push(atoi(pomoc));
}
else if(isdigit(string[j])&&(a.itop)){
cislo1 = int_pop();
vyb2 = pop();
char pomoc[2];
pomoc[0] = string[j];
pomoc[1] = '\0';
cislo2 = atoi(pomoc);
if(vyb2 == '+')
vysledok = cislo1+cislo2;
else if(vyb2 == '-')
vysledok = cislo1-cislo2;
else if(vyb2 == '*')
vysledok = cislo1*cislo2;
else if(vyb2 == '/')
vysledok = cislo1 / cislo2;
//printf(" v %d",vysledok);
int_push(vysledok);
}
}
printf("%d\n",int_pop());
}
}
/* Function to add an element to the stack */
void push (char c)
{
s.top++;
s.stk[s.top] = c;
//printf ("pushed element is = %c \n", s.stk[s.top]);
}
/* Function to delete an element from the stack */
char pop ()
{
char num = s.stk[s.top];
// printf ("poped element is = %c\n", s.stk[s.top]);
s.top--;
return(num);
}
int empty()
{
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
return 1;
}
void display ()
{
int i;
if (!empty)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\n The status of the stack is \n");
for (i = s.top; i >= 0; i--)
{
printf ("%c\n", s.stk[i]);
}
}
printf ("\n");
}
void int_push (int c)
{
a.itop++;
a.stk[a.itop] = c;
//printf ("pushed element is = %d \n", a.stk[a.itop]);
}
/* Function to delete an element from the stack */
int int_pop ()
{
int num = a.stk[a.itop];
// printf ("poped element is = %d\n", a.stk[a.itop]);
a.itop--;
return(num);
}
Is there any other way to create a calculator with priority, which can give good answers?
Thanks for your respond
Put breakpoints - you'll get the following expression:
+ + * 2 5 2 5. The problem with that, is your interpreter is interpeting this as (2+5+2)*5 instead of (2+5) * (2+5).
Well then, you might be wondering how to solve this. There's no simple single solution - you could either fix your own interpreter or build a whole new mechanic, because the way you build expressions just can't handle more then one pair of parthesises.
For example, you may want to calculate all the values in parnthesises before even building the expression seperatley, possibly using recursion in the case of parenthesiseception - however if you actually choose to use that method, you might want to change the way you work with the expressions entirely, because that's a different approach.
If you need me to show actual code examples to explain this further using parts of the code you made, just ask for it and i'll edit and provide what you need.
Either way, I really advise you to look up working with interpreters in general - you could really learn a lot about analysing strings and working with different inputs, and people even did similar stuff to yours with calculators before
EDIT: you asked for examples, so here you go - this is an example of a completely different method using recursion. This way, you handle a single pair of parenthesises at a time, and thus you won't have the problem you currently do. Note - the source i'm basing this on ( pretty much copy-pasted with edits from the thread and some personal comments ) is from codereview on stack exchange, you can see it here
if you're intrested.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void getInput(char * in) {
printf("> ");
fgets(in, 256, stdin);
}
int isLeftParantheses(char p) {
if (p == '(') return 1;
else return 0;
}
int isRightParantheses(char p) {
if (p == ')') return 1;
else return 0;
}
int isOperator(char p) {
if (p == '+' || p == '-' || p == '*' || p == '/') return p;
else return 0;
}
int performOperator(int a, int b, char p) {
switch(p) {
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/':
if (b == 0) { printf("Can't divide by 0, aborting...\n"); exit(1); } // now we dont want the world to expload here do we.
return a/b;
default:
puts("Bad value in switch.\n"); // A replacement which was mentioned in the thread- better have a default response just in case something goes wrong.
break;
}
return 0;
}
char isDigit(char p) {
if (p >= '0' && p <= '9') return 1;
else return 0;
}
int charToDigit(char p) {
if (p >= '0' && p <= '9') return p - '0';
else return 0;
}
int isNumber(char * p) {
while(*p) {
if (!isDigit(*p)) return 0;
p++;
}
return 1;
}
int len(char * p)
{
return (int) strlen(p); // This was bugged in the source, so I fixed it like the thread advised.
}
int numOfOperands(char * p) {
int total = 0;
while(*p) {
if (isOperator(*p)) total++;
p++;
}
return total+1;
}
int isMDGRoup(char *p)
{
for(; *p; p++) // used to be a while loop in the source, but this is better imho. more readable, also mentioned on the thread itself.
{
if (!isDigit(*p) && *p != '/' && *p != '*') return 0;
}
return 1;
}
int getLeftOperand(char * p, char * l) {
// Grab the left operand in p, put it in l,
//and return the index where it ends.
int i = 0;
// Operand is part of multi-*/ group
if (isMDGRoup(p)) {
while(1) {
if (*p == '*' || *p == '/') break;
l[i++] = *p++;
}
return i;
}
// Operand is in parantheses (so that's how you write it! sorry for my bad english :)
if(isLeftParantheses(*p)) {
int LeftParantheses = 1;
int RightParantheses= 0;
p++;
while(1) {
if (isLeftParantheses(*p)) LeftParantheses++;
if (isRightParantheses(*p)) RightParantheses++;
if (isRightParantheses(*p) && LeftParantheses == RightParantheses)
break;
l[i++] = *p++;
}
// while (!isRightParantheses(*p)) {
// l[i++] = *p++;
// }
l[i] = '\0';
return i+2;
}
// Operand is a number
while (1) {
if (!isDigit(*p)) break;
l[i++] = *p++;
}
l[i] = '\0';
return i;
}
int getOperator(char * p, int index, char * op) {
*op = p[index];
return index + 1;
}
int getRightOperand(char * p, char * l) {
// Grab the left operand in p, put it in l,
//and return the index where it ends.
while(*p && (isDigit(*p) || isOperator(*p) ||
isLeftParantheses(*p) || isRightParantheses(*p))) {
*l++ = *p++;
}
*l = '\0';
return 0;
}
int isEmpty(char * p) {
// Check if string/char is empty
if (len(p) == 0) return 1;
else return 0;
}
int calcExpression(char * p) {
// if p = #: return atoi(p)
//
// else:
// L = P.LeftSide
// O = P.Op
// R = P.RightSide
// return PerformOp(calcExpression(L), calcExpression(R), O)
// ACTUAL FUNCTION
// if p is a number, return it
if (isNumber(p)) return atoi(p);
// Get Left, Right and Op from p.
char leftOperand[256] = ""; char rightOperand[256]= "";
char op;
int leftOpIndex = getLeftOperand(p, leftOperand);
int operatorIndex = getOperator(p, leftOpIndex, &op);
int rightOpIndex = getRightOperand(p+operatorIndex, rightOperand);
printf("%s, %c, %s", leftOperand, op, rightOperand);
getchar();
if (isEmpty(rightOperand)) return calcExpression(leftOperand);
return performOperator(
calcExpression(leftOperand),
calcExpression(rightOperand),
op
);
}
int main()
{
char in[256];
while(1) {
// Read input from user
getInput(in);
if (strncmp(in, "quit", 4) == 0) break;
// Perform calculations
int result = calcExpression(in);
printf("%d\n", result);
}
}

How can I merge N files

I have N files, in each lines of every file there are unique words and the word count, for example
file1 file2 file3
the 2 black 3 red 4
apple 4 tree 2 crab 6
snake 3 mantle 8 puppet 1
How can I merge these files in sorted order into a one file, thanks in advance, really need an idea.
void *doMerge(void* arg){
int i,j,p = 0, k = 0;
char*min = malloc(sizeof(char)*256);
FILE *f = fopen("fileFinal","w+");
char **StringBuffer = (char **)malloc(sizeof(char*)*R);
int *IntBuffer = malloc(sizeof(int)*R);
for(i=0; i < R; i++){
rewind(temp2[i]);
StringBuffer[i] = (char *)malloc(sizeof(char)*256);
if(fscanf(temp2[i],"%s %d",StringBuffer[i],&IntBuffer[i]) == 1)
printf("String is %s and int is %d\n",StringBuffer[i],IntBuffer[i]);
}
while(1){
strcpy(min, StringBuffer[0]);
for(j=0 ; j < R-1; j++){
if(strcmp(StringBuffer[j+1],StringBuffer[j]) <= 0){
strcpy(min,StringBuffer[j+1]);
p = j+1;
}
}fprintf(f,"%s %d\n",min, p);
if(fscanf(temp2[p],"%s %d",StringBuffer[p],&IntBuffer[p]) == 1){}
k++;
}
};
while(1)
{
strcpy(min, StringBuffer[0]);
for(j=0 ; j < R-1; j++){
if(strcmp(StringBuffer[j+1],StringBuffer[j]) <= 0)
{
strcpy(min,StringBuffer[j+1]);
p = j+1;
}
}
fprintf(f,"%s %d\n",min, p);
if(fscanf(temp2[p],"%s %d",StringBuffer[p],&IntBuffer[p]) == 1)
{}
k++;
}
That while loop has a number of different problems
1) p needs to be initialized to 0 before the for loop
2) the strcmp should compare min to StringBuffer[j], which also means that
2a) the for loop should be for(j=1;j<R;j++), and
2b) strcpy(min,StringBuffer[j+1]); should be strcpy(min,StringBuffer[j]);, and
2c) the line p=j+1 should be p=j
3) k is not used for anything and should be removed
But the most important thing is the fscanf. You should be checking that fscanf returns 2. If not then the file is done, and you need to keep track of the fact that the file is done, and that file should not be checked in the for loop any more.

Access to a specific element on an array using pointers C

I am working to replace '.' by '::' in a phrase.
I am given a phrase with 30 caracteres, without using other array. I would like to access to the last element using a pointer.
However,
First I count the dots in my phrase.
actualSize= 0; i= 0; dotNumb= 0;
while (i<actualSize){
if (tab[i]=='.') dotNumb++
i++
}
Now I should start by the end; whenever I find an element I move it, whenever I find a '.' I make an operation two times, by copying ':' two times.
Now I need to access to this element tab[dotNumb+actualSize]
Can I do it this way, or should I use pointers .
int newSize = dotNumb+actualSize ;
int j=newSize ;
int cursor=actualSize;
while (j>0){
if (tab[i]!='.') {tab[j]=tab[cursor]; }
else{tab[j]=':';tab[--j]=':';}
cursor--; j--;
}
The code you wrote does not work, (you made some typos, for example actualSize is set to 0 so the loop counting the dots will never execute. and the logic of your code would delete the character preceding a dot in the original array). You probably want something like that:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char *tab = malloc(30 + 1);
if (tab == NULL) {
return -1;
}
strcpy(tab, "123456789.123456789.123456789.");
printf("Original string: %s\n", tab);
size_t actualSize = strlen(tab);
int dotNumb = 0;
for (int i = 0; i < actualSize; i++) {
if (tab[i]=='.') {
dotNumb++;
}
}
const size_t newSize = dotNumb + actualSize + 1;
tab = realloc (tab, newSize);
if (tab == NULL) {
/* leak memory previously allocated in tab */
return -1;
}
tab[newSize] = '\0'; /* termination character */
int j = newSize ;
for (size_t cursor = actualSize; cursor > 0; cursor--) {
if (tab[cursor] != '.') {
tab[j--] = tab[cursor];
}
else {
tab[j--] = ':';
tab[j--] = ':';
}
}
printf("Modified string: %s\n", tab);
return 0;
}
You can test the code here:
http://ideone.com/YOxJKo

Resources