Search code examples
arraysccharprintfc-strings

I'm having a problem with sending a char pointer to a function and assigning a value to it in C


I am trying to register to the address I sent to the function in the code structure you see below. But the for loop itself adds something. It only does this on arrays of 11 elements. That is, if "Hasan Polat" comes, he adds it, but if "Hasann Polat" comes, he does not add it. Or anything other than any 11 element array.printf output is written next to it

void sezarSifreleme(char cumle[], int kaydirma, char *sifreliCumle) {
    
      char alfabe[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
      int i,j, cumleUzunluk = strlen(cumle);

      for(i=0; i < cumleUzunluk; i++) {
          if(cumle[i]==' ') {
              cumle[i] = ' ';
          } else {
          for(j=0;j < 26; j++){
              if(cumle[i] == alfabe[j]){
                  j = j + kaydirma;
                  j = j % 26; // Sezar sifrelemede sona geldikten sonra basa donulur onu saglamak amacli 26'ya mod aliriz.
                  cumle[i] = alfabe[j];
                  break;
              }
          }
       }


printf("**");
// Sonucu main fonk icerisine gondermek icin aldigimiz degisken adresine sifreledigimiz cumleyi atiyoruz
for(i=0; i < cumleUzunluk; i++) {
    
    sifreliCumle[i] = cumle[i];
    printf("%c", sifreliCumle[i]); // **mfxfs utqfy**
}
printf("**");

printf("??%s??", sifreliCumle); // ??mfxfs utqfy??
}

Solution

  • Taking into account these two outputs: one with the fixed number of characters cumleUzunluk in the for loop

    printf("**");
    // Sonucu main fonk icerisine gondermek icin aldigimiz degisken adresine sifreledigimiz cumleyi atiyoruz
    for(i=0; i < cumleUzunluk; i++) {
        
        sifreliCumle[i] = cumle[i];
        printf("%c", sifreliCumle[i]); // **mfxfs utqfy**
    }
    printf("**");
    

    and other with using the conversion specifier s

    printf("??%s??", sifreliCumle); // ??mfxfs utqfy??
    

    it means that at least the pointer sifreliCumle does not point to a string.

    You could rewrite this call of printf the following way

    printf("??%.*s??", cumleUzunluk, sifreliCumle);
    

    or append the zero character '\0' provided that the array pointed to by the pointer sifreliCumle have a space to store the zero character '\0' as for example

    sifreliCumle[cumleUzunluk] = '\0';
    printf("??%s??", sifreliCumle);