您已選擇寫:
while(ptr!='\0')
這是寫作的一種有趣的方式:在這裏你打算寫
while (ptr != NULL)
:
while (ptr != 0)
或:
while (*ptr != '\0')
傳統的寫作方式*(pointer+cnt)
是pointer[cnt]
。
你不能釋放遞增的指針;你必須釋放什麼被malloc()
返回 - 或calloc()
或realloc()
或...
保留通過binary_decimal()
返回的值的副本,並釋放副本(或ptr
增加複製和自由的價值)。
您可以在下面的代碼中使用任意兩個binary_decimal()
功能:
#include <stdio.h>
#include <stdlib.h>
char *decimal_binary(int);
int main(void)
{
int n;
char *ptr = NULL;
printf("Enter the number\n");
scanf("%d", &n);
ptr = decimal_binary(n);
char *cpy = ptr;
//printing out the characters
while (*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
putchar('\n');
free(cpy);
return 0;
}
char *decimal_binary(int n)
{
int cnt = 0;
char *pointer = (char *)malloc(8 + 1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (int c = 7; c >= 0; c--)
{
int d = n >> c;
if (d & 1)
pointer[cnt] = 1 + '0';
else
pointer[cnt] = 0 + '0';
cnt++;
}
pointer[cnt] = '\0';
return pointer;
}
或者:
char *decimal_binary(int n)
{
int cnt = 0;
char *pointer = (char *)malloc(8 + 1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (int c = 7; c >= 0; c--)
pointer[cnt++] = ((n >> c) & 1) + '0';
pointer[cnt] = '\0';
return pointer;
}
這可以被壓縮更(甚至更少的可讀取):
char *decimal_binary(int n)
{
char *pointer = (char *)malloc(8 + 1);
if (pointer == NULL)
exit(EXIT_FAILURE);
for (int c = 7; c >= 0; c--)
pointer[7 - c] = ((n >> c) & 1) + '0';
pointer[8] = '\0';
return pointer;
}
而對於一個9字節的緩衝區,你完全可以在01中分配一個局部變量並通過地址decimal_binary()
所以它並不需要使用malloc()
和main()
不需要使用免費:
#include <stdio.h>
#include <stdlib.h>
void decimal_binary(int, char *);
int main(void)
{
int n;
char buffer[9];
char *ptr = buffer;
printf("Enter the number\n");
scanf("%d", &n);
decimal_binary(n, buffer);
while (*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
putchar('\n');
return 0;
}
void decimal_binary(int n, char *pointer)
{
for (int c = 7; c >= 0; c--)
pointer[7 - c] = ((n >> c) & 1) + '0';
pointer[8] = '\0';
}
寫入'*(指針+ CNT)的傳統方法'是'指針[CNT] '。 –
你不能釋放遞增的指針;你必須釋放'malloc()' - 或'calloc()'或'realloc()'返回的內容或者...保留返回值的副本。 –
@喬納森..感謝您的回答,我意識到空字符('\ 0)和空指針之間的區別。還有關於釋放指針的更正幫助。 – Rommel