简体   繁体   English

C中的字符串串联

[英]String concatenation in C

So I got this function which is able to put a space infront of a "/" C if there is no space. 所以我得到了这个函数,如果没有空间,该函数可以在“ /” C前面放置一个空格。 And it cuts up the string fine but I get an error, possibly a memory violation when I try to concat the string together. 并且它可以减少字符串,但是当我尝试将字符串连接在一起时,我收到错误,可能是内存违规。 Please give me a hand. 请帮帮忙。

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

char* substr(const char *pstr, int start, int numchars) {
    char* pnew = malloc(numchars + 1);
    strncpy(pnew, pstr + start, numchars);
    pnew[numchars] = '\0';
    return pnew;
}

char* fixString(char str[]) {
    char* position;
    char* newString = "";
    char* finalString;

    int oldPosition = 0;
    printf("Original str: %s\n", str);
    printf("Original length: %d\n\n", strlen(str));

    position = strchr(str, '/');
    while (position != NULL) {
        int charPosition = position - str;

        printf("String position: %d->%d\n", oldPosition, charPosition);
        newString = substr(str, oldPosition, charPosition - oldPosition);
        oldPosition = charPosition;
        if (charPosition > 0 && str[charPosition - 1] != ' ') {
            printf("Previous char: %c\n", str[charPosition - 1]);
            newString = strcat(newString, " ");
        }

        printf("String: |%s|\n", newString);
        if (strlen(newString) > 0) {
            finalString[0] = strcat(finalString, newString);
        }
        printf("------------\n");
        position = strchr(position + 1, '/');
    }
    char* lastString = substr(str, oldPosition, strlen(str));
    finalString = strcat(finalString, lastString);
    printf("lastString: %s\n\n", lastString);
    return finalString;
}

int main() {
    char* testString = "/Filter /FlateDecode/Length 7108/Subtype /Type1C";
    printf("%s", fixString(testString));

    return 0;
}

You never allocate a target buffer. 您永远不会分配目标缓冲区。 The finalString variable isn't initialised to anything. finalString变量未初始化为任何东西。

That's not the only problem with your code, either. 这也不是代码的唯一问题。 You seem to be treating the char * as some kind of smart string type, but it is nothing more than a pointer into a memory location. 您似乎将char *视为某种智能字符串类型,但它不过是指向内存位置的指针。 For instance, this: 例如,这个:

newString = strcat(newString, " ");

doesn't concatenate two strings and return the concatenated result. 不连接两个字符串并返回连接结果。 It appends a space onto the char buffer newString points to and returns the same buffer. 它在char缓冲区中追加一个空格,newString指向并返回相同的缓冲区。 Assigning to newString is harmless, but misleading. 分配给newString是无害的,但具有误导性。

// It is the callers responsibility to free the returned string.
char *fixString(char *str) {
    int len;
    char *s;
    char *dest;
    int after_space;

    // First pass, figure out the size of the output.
    len = 0;
    after_space = 0;
    for (s = str; *s; s++) {
        len += 1 + (!after_space && *s == '/');
        after_space = *s == ' ';
    }
    dest = malloc(len + 1);

    s = dest;
    after_space = 0;
    while(*str) {
        if (!after_space && *str == '/') *s++ = ' ';
        after_space = (*s++ = *str++) == ' ';
    }
    return dest;
}

You need to allocate some memory for finalString . 你需要为finalString分配一些内存。

Try doing it like this: 尝试这样做:

#define BUFFER_SIZE 1024
char* finalString = malloc(BUFFER_SIZE);
// ...
strncat(finalString, "something", 1024);

Remember to call free() on the pointer when you don't need it anymore (not in your function - after the function returns, somewhere in client code, whenever the result's not needed). 记得在你不再需要它时调用指针上的free() (不是在你的函数中 - 在函数返回之后,在客户端代码中的某个地方,只要不需要结果)。

You never malloc memory for your newString and finalString pointers. 你永远不malloc内存为您newStringfinalString指针。 strcat expects that the destination pointer you give it has enough space to store the strings. strcat期望你给它的目标指针有足够的空间来存储字符串。

You might also have to check for the size after malloc() and realloc() if necessary. 必要时,您可能还必须检查malloc()和realloc()之后的大小。 Welcome to the beautiful world of memory management in C :) 欢迎来到美丽的C语言内存管理世界:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM