您已选择写:
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