这段代码有什么问题?

发布于 2024-12-04 08:19:49 字数 793 浏览 1 评论 0原文

正如你在下面看到的,我创建了一个小程序来使用 C 连接 2 个字符串,正如你可能想象的那样,这段代码不起作用,我已经通过使用数组表示法而不是指针自行更正了它,并且它工作得很好,但是我仍然不确定为什么我的代码几乎无法成为我更正代码的复制品。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void concatena(char *str1, char *str2){
 char *strAux;
 int mover;
 mover = 0;
 strAux = (char *)(malloc(strlen(str1) + strlen(str2)+2));
 *(strAux) = '\0';
 if(str1 == '\0')
    *strAux = '\0';
 else
     while(str1 != '\0'){
         *(strAux+mover++)=*(str1++);
     }
 if(str2 == '\0')
         *strAux = '\0';
 else
     while(str2 != '\0'){
         *(strAux+mover++)=*(str2++);
     }
 strAux='\0';
 str1=strAux;
 printf("%s", str1);
 free(strAux);
 }

我仍然是一个 C 初学者(是的,我知道有像 string.h 这样的库,我问这个是出于学术原因)并且我被告知 char 指针和数组是同一件事,让我很困惑。

非常感谢任何帮助。

As you can see below I have created a little program to concatenate 2 strings using C, as you may imagine this code doesn't work, I have already corrected it myself by using Array notation instead of pointers, and it works just fine, however I'm still not sure why is it that my code fails being almost a replica of my corrected code.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void concatena(char *str1, char *str2){
 char *strAux;
 int mover;
 mover = 0;
 strAux = (char *)(malloc(strlen(str1) + strlen(str2)+2));
 *(strAux) = '\0';
 if(str1 == '\0')
    *strAux = '\0';
 else
     while(str1 != '\0'){
         *(strAux+mover++)=*(str1++);
     }
 if(str2 == '\0')
         *strAux = '\0';
 else
     while(str2 != '\0'){
         *(strAux+mover++)=*(str2++);
     }
 strAux='\0';
 str1=strAux;
 printf("%s", str1);
 free(strAux);
 }

I´m still a C beginner (And yes, I'm aware that there are libraries like string.h, I'm asking this for academic reasons) and I have been told that char pointers and arrays are the same thing, something that confuses the heck out of me.

Any help is greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

赠我空喜 2024-12-11 08:19:49

我看到的第一个问题是在这一部分:

if(str2 == '\0')
    *strAux = '\0';

就在这段代码之前,您已经用 str1 中的字符串填充了 strAux
然后,如果 str2 为空,您会突然在 strAux 的开头放置一个空终止符,从而消除了您迄今为止所做的所有工作!

我认为你的意图是:

if(*str2 == '\0')
     *(strAux+mover) = '\0';

str2 循环之后再次发生同样的事情,你有代码:

strAux='\0';

同样,这在 strAux 的开头放置了一个空终止符,有效地结束了新创建的字符串在它开始之前。


这是我重写你的代码的方式:

void concatena(char *str1, char *str2){
    char *strAux;
    int mover = 0;

    strAux = (char *)(malloc(strlen(str1) + strlen(str2)+1));  // Changed to +1, NOT +2
    *(strAux) = '\0';   // Start the string as (empty)

    while(*str1 != '\0'){   // Copy the first string over.
         *(strAux+mover++)=*(str1++);
    }

    while(*str2 != '\0'){   // Copy the second string over.
         *(strAux+mover++)=*(str2++);
    }

    *(strAux+mover)='\0';  // End the new, combined string.

    printf("%s", strAux);  // Show the results.
    free(strAux);
 }

The first problem I see is with this section:

if(str2 == '\0')
    *strAux = '\0';

Just before this code, you've filled up strAux with the string from str1.
Then, if str2 is empty, you suddenly put a null-terminator at the beginning of strAux, eliminating all the work you've done so far!

I think what you intend is:

if(*str2 == '\0')
     *(strAux+mover) = '\0';

Its the same thing again after your loop for str2, you have the code:

strAux='\0';

Again, this puts a null-terminator at the start of strAux, effectively ending the newly created string before it even gets started.


Here's how I'd re-write your code:

void concatena(char *str1, char *str2){
    char *strAux;
    int mover = 0;

    strAux = (char *)(malloc(strlen(str1) + strlen(str2)+1));  // Changed to +1, NOT +2
    *(strAux) = '\0';   // Start the string as (empty)

    while(*str1 != '\0'){   // Copy the first string over.
         *(strAux+mover++)=*(str1++);
    }

    while(*str2 != '\0'){   // Copy the second string over.
         *(strAux+mover++)=*(str2++);
    }

    *(strAux+mover)='\0';  // End the new, combined string.

    printf("%s", strAux);  // Show the results.
    free(strAux);
 }
葬心 2024-12-11 08:19:49

接受相同的约束,以下是我将如何(重新)编写您的代码。不幸的是,存在一个规范缺陷:串联是否应该发生在传递的第一个字符串上?或者应该创建一个新字符串?以下是这两种方法:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char *concatena (const char *str1, const char *str2)
{
        char    *op, *newStr = (char*)malloc (strlen (str1) + strlen (str2) + 1);
        if (!newStr)
        {
                fprintf (stderr, "concatena: error allocating\n");
                return;
        }

        op = newStr;    // set up output pointer
        while (str1 && *str1)   // copy first string
                *op++ = *str1++;

        while (str2 && *str2)   // concatenate second string
                *op++ = *str2++;

        *op = '\000';           // add conventional NUL termination

        return newStr;
}


void concatenb (char *str1, const char *str2)
{
        char    *op;
        if (!str1)
        {
                fprintf (stderr, "concatenb: NULL string 1\n");
                return;
        }

        op = &str1 [strlen (str1)];     // set output pointer at trailing NUL

        while (str2 && *str2)   // concatenate second string
                *op++ = *str2++;

        *op = '\000';           // add conventional NUL termination
}

Accepting the same constraints, here is how I would (re)write your code. Unfortunately there is a specification shortcoming: should the concatenation occur to the first string passed? Or should a new string be created? Here are both methods:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char *concatena (const char *str1, const char *str2)
{
        char    *op, *newStr = (char*)malloc (strlen (str1) + strlen (str2) + 1);
        if (!newStr)
        {
                fprintf (stderr, "concatena: error allocating\n");
                return;
        }

        op = newStr;    // set up output pointer
        while (str1 && *str1)   // copy first string
                *op++ = *str1++;

        while (str2 && *str2)   // concatenate second string
                *op++ = *str2++;

        *op = '\000';           // add conventional NUL termination

        return newStr;
}


void concatenb (char *str1, const char *str2)
{
        char    *op;
        if (!str1)
        {
                fprintf (stderr, "concatenb: NULL string 1\n");
                return;
        }

        op = &str1 [strlen (str1)];     // set output pointer at trailing NUL

        while (str2 && *str2)   // concatenate second string
                *op++ = *str2++;

        *op = '\000';           // add conventional NUL termination
}
花间憩 2024-12-11 08:19:49
strAux = (char *)(malloc(strlen(str1) + strlen(str2)+2));

2 不是必需的,只需 1 作为终止字符就足够了。

*(strAux) = '\0';

这应该只在所有计算结束时发生。不在串联之间,即

while(*str1 != '\0'){  // This loops copies the first string
    // ^ Notice that you need to dereference to check for the termination character.
     *(strAux+mover++)=*(str1++);
}
while(*str2 != '\0'){  // This loop copies the second string
     *(strAux+mover++)=*(str2++);
}
// Finally adding termination character
*(strAux+mover) = '\0'; // since with mover you are keeping track of locations.
strAux = (char *)(malloc(strlen(str1) + strlen(str2)+2));

2 is not required, just 1 is sufficient for the termination character.

*(strAux) = '\0';

This should be happening only at the end of all your computation. Not in between the concatenation i.e.,

while(*str1 != '\0'){  // This loops copies the first string
    // ^ Notice that you need to dereference to check for the termination character.
     *(strAux+mover++)=*(str1++);
}
while(*str2 != '\0'){  // This loop copies the second string
     *(strAux+mover++)=*(str2++);
}
// Finally adding termination character
*(strAux+mover) = '\0'; // since with mover you are keeping track of locations.
千纸鹤带着心事 2024-12-11 08:19:49

代码中的错误数量令人沮丧。您或许应该拿起一本好的 C 书籍并重新开始。

首先,有一个库函数可用于连接字符串:

const unsigned int len = strlen(str1) + strlen(str2) + 1;
char * dst = malloc(len);
strncat(dst, str1, len);
strncat(dst, str2, len);

现在,如果您坚持手动执行此操作,则必须正确获取指针和取消引用:

char * d = dst;
while (*str1 != 0) *dst++ = *str1++;
while (*str2 != 0) *dst++ = *str2++;
*dst = 0;
// d now points to the beginning of the concatenated string

这两个循环检查输入字符串中的当前字符是否为非零,并且如果是,则它们将该字符复制到输出字符串中的当前字符,然后输入和输出指针都前进。 (这一切都是通过使用后缀 ++ 运算符一次完成的。)最后,最后一个字符设置为零以创建一个新的空终止符。

在此过程中,我们修改了所有三个指针dststr1str2。后两个通过复制作为输入函数参数传入,所以没关系。为了返回连接的字符串,我们在循环之前制作了 dst 的副本,我们可以在最后返回它。

The amount of errors in your code is disheartening. You should probably pick up a good C book and start over.

First off, there's a library function that you can use to concatenate strings:

const unsigned int len = strlen(str1) + strlen(str2) + 1;
char * dst = malloc(len);
strncat(dst, str1, len);
strncat(dst, str2, len);

Now, if you insist on doing it manually, you have to get pointers and dereferencing right:

char * d = dst;
while (*str1 != 0) *dst++ = *str1++;
while (*str2 != 0) *dst++ = *str2++;
*dst = 0;
// d now points to the beginning of the concatenated string

The two loops check if the current character in the input string is nonzero, and if so, then they copy that character to the current character in the output string, and then both input and output pointer are advanced. (This is all done in one wash by use of the postfix ++ operator.) Finally, the last character is set to zero to create a new null-terminator.

In the process we modified all three pointers dst, str1 and str2. The latter two came in as input function arguments by copy, so that's fine. For returning the concatenated string we made a copy of dst before the loop, which we can return in the end.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文