AndyM AndyM - 2 months ago 5
C Question

copying int to a string

I'am trying to learn c and therefore solving this exercise. My problem is in the part where I have to abbreviate a word. I am using sprintf to convert the integer to a string and write it into my old string. But however I try to achieve it, the last character of the string always gets lost. Why does this happen? Here is the code:

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

void abreviation(char *arr,int length){
if ( length+1 > 10){
char c = arr[length];
sprintf(arr+1, "%d%c", length-1,c);
}
}

int main() {
int n,i,j;
scanf("%d\n",&n);
char **arr = malloc(n*sizeof(char*));
for(i=0; i < n ; i++){
arr[i] = malloc(sizeof(char)*100);
char c;
for ( j=0; (c = getchar()) != '\n' ; j++)
arr[i][j]=c;
arr[i][j+1]='\0';
abreviation(arr[i],j);
}
for(i=0; i < n; i++)
printf("%s\n", arr[i]);

}


I appreciate any help.

Answer

The loop you wrote to input the words stop at '\0', at that point j is indexed to '\0', and then in the abreviation function char c = arr[length c will always be \0 and not the last char in the word (arr).

A simple fix is to change

abreviation(arr[i],j);

to

abreviation(arr[i],j-1);
Comments