我要在程序中执行的操作是将一个字符串的内容反向复制到另一个字符串。该程序的这一部分工作。
但是,我不想限制用户的输入,因此我想使用malloc和realloc。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
while (c!='\n')
{
/*reallocate if needed*/
if (i==(end-1)){
end*=2;
temp = realloc(p,end*sizeof(temp));
if (temp!=NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else
free(p);
}
c=getchar();
p[i]=c;
i++;
}
char h [sizeof(p)];
copyStr(p,h);
}
我发现realloc函数无法正常工作,因此我正在寻求您的帮助。
如果输入非常短(即3个字符),则该程序可以运行。如果长度超过10个字母,它将不会重新分配内存。如果长度超过5,它将反向打印,但会向我发送一条信息,即“堆栈已砸”。谢谢你。
实际上,有一些小技巧可以更改:
*temp=realloc(...
应成为temp=realloc(...
temp!=NULL
是的正常行为realloc()
。p
如果您在重新分配操作之后使用它,请不要忘记在更改之后进行更改。sizeof(p)
是指针的大小,即4或8 ...我把它变成了 char h [sizeof(char)*(i+1)];
\0
字符串的末尾添加了字符。如果您希望打印它或使用strlen()
和,则很有用#include string.h
。那么你就可以printf("the result is :\n%s \n",h);
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
//keep end-of-string character
h[length+1]='\0';
/* char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}*/
printf("the result is :\n%s \n",h);
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
//signaling end of string
p[0]='\0';
while (c!='\n' && c!=EOF)
{
/*reallocate if needed*/
if (i==(end-2)){
end*=2;
temp=(char*)realloc(p,end*sizeof(char));
if (temp==NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else{
p=temp;
printf("ok here\n");
}
}
c=getchar();
p[i]=c;
i++;
}
//signaling end of string
p[i+1]='\0';
printf("INVERTING STRING\n");
char h [sizeof(char)*(i+1)];
copyStr(p,h);
free(p);
}
!Enif krow ot smees ti
再见,
弗朗西斯(Francis)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句