剛接觸 c 并嘗試學習。在這里,我嘗試創建一個函式,該函式使用動態記憶體分配和 byref 將字串復制到第一個空間。好像我在使用 realloc 的方式上做錯了什么。你能幫我弄清楚我使用動態記憶體分配的方式有什么問題嗎?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void f1(char **c, char *s);
int main() {
char * s = "this is an example";
char *c;
c =(char *) malloc(sizeof(char));
f1(&c,s);
free(c);
}
void f1(char **c, char *s)
{
int i=0;
while ((s[i])!=' ')
{
(*c)[i]=s[i];
i ;
(*c)=(char *)realloc ((*c),sizeof(char)*i);
}
(*c)[i]='\0';
printf("\n%s\n",*c);
}
uj5u.com熱心網友回復:
void f1(char** r, char* s)
{
// find size of new buffer
size_t len = 0;
while(s[len] != '\0' && s[len] != ' ') len ;
*r = (char*)malloc(len 1);
memcpy(*r, s, len);
(*r)[len] = '\0';
}
uj5u.com熱心網友回復:
在函式呼叫之前,已經為一個字符分配了記憶體
c =(char *) malloc(sizeof(char));
在 while 回圈的第一次迭代中
int i=0;
while ((s[i])!=' ')
{
(*c)[i]=s[i];
i ;
(*c)=(char *)realloc ((*c),sizeof(char)*i);
}
這段記憶被填滿
(*c)[i]=s[i];
然后又只為一個字符分配了記憶體
(*c)=(char *)realloc ((*c),sizeof(char)*i);
因為在回圈的第一次迭代中i變得等于1。因此,在回圈的第二次迭代中,嘗試在分配的記憶體之外寫入會導致未定義的行為。
你至少需要寫
*c = realloc ( *c, i 1);
此外,使用中間指標會更安全,例如
char *tmp = realloc ( *c, i 1);
if ( tmp != NULL ) *c = tmp;
但在這種情況下,您還需要更改功能邏輯。
并且函式應該宣告為
int f1( char **c, const char *s);
并且應該改變的條件
while ( s[i] != '\0' && s[i] !=' ' )
使用您的方法,程式可以如下所示。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int f1( char **s1, const char *s2 );
int main( void )
{
const char *s = "this is an example";
char *t = malloc( sizeof( char ) );
if ( t != NULL )
{
t[0] = '\0';
f1( &t, s);
puts( t );
}
free( t );
}
int f1( char **s1, const char *s2 )
{
int success = 1;
for ( size_t i = 0; success && s2[i] != '\0' && !isblank( ( unsigned char )s2[i] ); i )
{
char *tmp = realloc( *s1, i 2 );
success = tmp != NULL;
if ( success )
{
*s1 = tmp;
( *s1 )[i] = s2[i];
( *s1 )[i 1] = '\0';
}
}
return success;
}
程式輸出為
this
然而,這種具有許多記憶體重新分配的方法效率低下。
我會用以下方式撰寫程式
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * f1( const char *s, const char *delim );
int main( void )
{
const char *s = "this is an example";
char *t = f1( s, " \t" );
if ( t != NULL )
{
puts( t );
}
free( t );
}
char * f1( const char *s, const char *delim )
{
size_t n = strcspn( s, delim );
char *result = malloc( n 1 );
if ( result != NULL )
{
result[n] = '\0';
memcpy( result, s, n );
}
return result;
}
程式輸出再次是
this
uj5u.com熱心網友回復:
正如@UnholySheep 提到的,i我用來分配記憶體的空間太小了。更改為(*t) = (char *)realloc((*t),(i 1)*sizeof(char));并且有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485114.html
上一篇:在C中可以交替管道嗎?
下一篇:復制在c中具有不同列的二維陣列
