0

您好,我是 C 语言的新手。基本上我正在尝试将 char 数组(字符串)的指针传递给一个函数,并且在该函数内我想在该数组的最后添加一个字符。这是我要运行的代码。

所以我说的函数是代码中的function1。指针线是我试图操纵的。我正在尝试通过使用方法追加在函数 1 内的行中再添加一个字符。我也尝试了一些其他方法,但没有一个真正奏效。

如果有人能告诉我如何正确地做到这一点,那将非常有帮助。

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

char* function1(char* );
void append(char* , char );

int main(int argc, char const *argv[])
{
    /* code */

    function1("each line ends with : ");
    return 0;
}

char* function1(char* line)
{
    int pos = 0;
    char* longest = "";


    printf("so far working!\n");
    append(line, '$');
    // here during append something happens and all it tells is segmentation fault core dumped
    printf("not anymore.\n");

    return longest;
}

void append(char* s, char c)
{
    s[strlen(s)] = c;
    s[strlen(s)+1] = '\0';
}
4

2 回答 2

2

The problem is that not enough space was allocated for your string - when you declare the string, you say "it will be no more than n bytes long" (including the terminating '\0'). Writing bytes in memory that doesn't belong to the string will give rise to the error you see.

There is no universal solution when you use C - in your example, you start out with a constant string (defined up front with "each line ends with: ") and the compiler only allocates that much space. If you think you might need more space, you could do something like this:

char mySpace[101];  // allocates 101 bytes : 100 characters + terminating '\0'
strncpy(mySpace, "each line ends with: ", 100); / copy at most 100 bytes

Now you can increase the length of mySpace by one character (unlike the original string, which was a constant because of the way you created it, you can do what you want with the copy as long as you stay within the limits of the memory you allocated for it):

int length;
length = strlen(mySpace);
mySpace[length] = '$';
mySpace[length+1] = '\0';

Does that make sense?

EDIT Just realized another problem:

In the code snippet

s[strlen(s)] = c;
s[strlen(s)+1] = '\0';

In the first line you overwrite the terminating '\0' character of the string: when you then call strlen in the second line, that function tries to find the end of line character (that no longer exists) and it runs off into the distance, all the way to a segmentation fault (which means roughly "the program ended up trying to access memory that did not belong to it"). When I wrote my code snippet I had instinctively done that the right way - then I looked at your code again and saw the problem stare me in the face.

于 2013-09-26T01:36:38.097 回答
0

当你在 C 中声明一个字符串时"like this",你实际上并没有得到一个char*. 你得到一个const char*(好吧,不是技术上的,但它通常在只读存储器中)。切勿尝试修改char*在字符串文字中声明的 a。

于 2013-09-26T01:38:33.513 回答