c-使用指针操作打印输入的字符串



我是指针新手,请告诉我如何打印输入的字符。

#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = malloc(32 * sizeof(char));
*ptr = 'h';
ptr++;
*ptr = 'e';
ptr++; 
*ptr = 'l';
ptr++;
*ptr = 'l';
ptr++;
*ptr = 'o';
ptr++;
*ptr = 'n';
printf("value entered is %sn", ptr);
return 0;
}

我想打印你好

您忘记了null终止符。添加此:

ptr++;
*ptr = '';

此外,指针现在指向null终止符(或以前的换行符(。您必须将其重新设置为指向'h':

ptr -= 6;

当你完成后,你应该释放内存:

free(ptr);

你应该用一个临时指针来修复你的代码:

#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char* ptr;
ptr = malloc(32 * sizeof(char));
if(ptr == NULL)
{
puts("Allocation failed");
return EXIT_FAILURE;
}
char* tmp = ptr;
*tmp = 'h';
tmp++;
*tmp = 'e';
tmp++; 
*tmp = 'l';
tmp++;
*tmp = 'l';
tmp++;
*tmp = 'o';
tmp++;
*tmp = ''; // NOTE: null termination not n
printf("value entered is %sn", ptr);
free(ptr);    
return 0;
}

一个没有混乱指针算法的正确版本如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char* ptr;
ptr = malloc(32 * sizeof(char));
if(ptr == NULL)
{
puts("Allocation failed");
return EXIT_FAILURE;
}
strcpy(ptr, "hello");
printf("value entered is %sn", ptr);
free(ptr);
return 0;
}

您可以使用malloc()函数,而不是使用calloc()函数,这实现了与malloc()相同的目标,但会用'\0'填充内存。这使得使用非固定长度的字符串更容易
您可以在此处找到此功能的文档。

这是我制作的代码:

#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = calloc(32,sizeof(char));
*ptr = 'h';
ptr++;
*ptr = 'e';
ptr++; 
*ptr = 'l';
ptr++;
*ptr = 'l';
ptr++;
*ptr = 'o';
ptr++;
*ptr = '';  //It should be null terminated
ptr -= 5;
printf("value entered is %sn", ptr);
free(ptr);
return 0;
}

最新更新