How printf processes its arguments when one is passed by reference to another argument

I found something interesting, but could not explain it. I am writing a simple procedure to change a string. This works fine, no complaints.

My problem is in printf. When I print the original line separately, it prints correctly, but when I print the original line as the first argument, and the function call is treated as the second, both are displayed as the inverse.

Exit:

|| abcdthelgko ||
Orig Str: | okglehtdcba |, Rev Str | okglehtdcba |

code:

char* ReverseStr(char* str, int len)
{
  char *start = &str[0], *end = &str[len-1];
  char temp;

  while(start < end)
  {
    temp = *start;
    *start = *end;
    *end = temp;

    start++;
    end--;
  }
  return str;
}

int main()
{
  char str_unique[] = "abcdthelgko";
  int str_unique_len = sizeof(str_unique)/sizeof(str_unique[0]);

  printf("\n || %s || \n", str_unique);
  printf("Orig Str: | %s |, Rev Str | %s |\n", str_unique, ReverseStr(str_unique, str_unique_len-1));
  return 0;
}

* : * 2 ,  1. Printf  2. , printf, , , . , : ================== ======================

 i = 5, changed i = 2, again i= 2 

 changed i = 2, i= 2 

 i = 5, changed i = 2 

================== ======================

int* change (int* addr);

int main()
{
  int i;
  i=5;
  printf("\n i = %d, changed i = %d, again i= %d \n ", i, *change(&i), i);

  i=5;
  printf("\n changed i = %d, i= %d \n", *change(&i), i);

  i=5;
  printf("\n i = %d, changed i = %d \n", i, *change(&i));
  return 0;
}

int* change (int* addr)
{
  *addr = 2;
  return (addr);
}
+4
4

ReverseStr ( ), "" .

, . :

printf("%lf", pow(2, 2));

power (pow) printf. , , printf , , " ".

- , ReverseStr, :

int main()
{
  char str_unique[] = "abcdthelgko";
  char *str_dup = strdup(str_unique);
  int str_unique_len = sizeof(str_unique)/sizeof(str_unique[0]);

  printf("\n || %s || \n", str_unique);
  printf("Orig Str: | %s |, Rev Str | %s |\n", str_unique,
      ReverseStr(str_dup, str_unique_len - 1));

  free(str_dup); // Don't forget to free the memory allocated by strdup!
  return 0;
}
+6

ReverseStr printf,
, str_unique, ReverseStr
:)

0

ReverseStr - , . ( , , , , - void).

, :

char* ReverseStr(char* str, int len) {
    char *reversed = malloc(len * sizeof(char));
    int i, j = len - 1;
    for (i = 0; j >= 0; i++) {
        reversed[i] = str[j--];
    }

    return reversed;
}

, ,

char* ReverseStr(char* str, int len) {
    char *start = &str[0], *end = &str[len-1];
    char temp;
    int i;

    char *original = malloc(len * sizeof(char));
    for (i = 0; str[i] != '\0'; i++) {
        original[i] = str[i];
    }

    while (start < end) {
        temp = *start;
        *start = *end;
        *end = temp;

        start++;
        end--;
    }
    return original;
}
0

ReverseStr() in-situ, .

C . printf() , ReverseStr(), ( str_unique), str_unique , ReversStr().

, . (malloc) ReverseStr ( ), .

-1

Source: https://habr.com/ru/post/1615703/


All Articles