[英]using pointer index trying to reverse a string in c
void funrev( char * str)
{
int n = strlen(str);
char *ptr2 = (char*)malloc( n +1);
char* ptr = ptr2;
while( *str)
{
str++;
}
int i;
for(i =0; i <=n ; i++)
{
*(ptr++) = str[--n];
}
*ptr = '\0';
printf(" rev %s", ptr2);
}
我正在嘗試使用指針索引反轉字符串,使用索引遞減指針並分配給指針。 請指出這有什么問題。
您將str
指針移動到字符串的末尾:
while( *str) {
str++;
}
然后索引過去:
*(ptr++) = str[--n]
這個字節str[--n]
是通過str
末尾的n-1
字符,這可能不是您想要的。 這里還有其他錯誤,比如你正在遞減n
和遞增i
,這也可能不是你想要的。
您的代碼的工作版本可能如下所示:
void funrev(const char *str)
{
int n = strlen(str);
char *reversed = malloc(n + 1);
const char *end_of_str = str + n;
for (size_t i = 0; i < n; i++)
reversed[i] = *(--end_of_str);
reversed[n] = 0;
printf("rev %s\n", reversed);
free(reversed);
}
您需要創建本地版本嗎? 你正在返回void
所以我假設你想反轉str
,這可能比你在做什么更清楚。 它使用char
將前導與尾隨字符交換。
void funrev(char* str)
{
size_t len = strlen(str);
if (len < 2)
{
return; /* nothing to do */
}
char *lp = str; /* pointer to lead character */
char *tp = str + len - 1; /* pointer to tail character */
char swap;
size_t loops = len / 2; /* fractional part is truncated */
for (size_t loop = 0; loop < loops; loop++)
{
swap = *lp; /* swap */
*lp = *tp;
*tp = swap;
lp++; /* increment lead pointer */
tp--; /* decrement tail pointer */
}
return;
}
void funrev( char * str)
{
int n = strlen(str);
char *ptr2 = (char*)malloc( n +1);
char* ptr = ptr2;
while( *str)
{
str++; // error1: moving str pointer..; why is the requirement for this?
}
int i;
for(i =0; i <=n ; i++)
{
*(ptr++) = str[--n]; // error2: wrong use of n variable, decrementing n will effect the loop..
}
*ptr = '\0';
printf(" rev %s", ptr2);
}
你可能需要這個...
int funrev( char * str)
{
int n = strlen(str);
char *ptr2 = (char*)malloc( n +1);
char* ptr = ptr2;
if(!(*str)) // error handling
{
printf("null string: nothing to reverse!\n");
return -1;
}
int i,lastindex = n; //edit...
for(i =0; i <=n ; i++)
{
*(ptr+i) = str[lastindex--]; //edit...
}
*(ptr+i+1) = '\0'; //edit...
printf(" rev %s", ptr2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.