AndyM AndyM - 3 months ago 10
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;
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++)
for(i=0; i < n; i++)
printf("%s\n", arr[i]);


I appreciate any help.


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