This question already has answers here:
Modify a string with pointer [duplicate]
                                
                                    (4个答案)
                                
                        
                        
                            Code not working as expected in C
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
我已经编写了将数据存储在文本文件中的代码,并且将数据分为2个字符串。而且我确实使用strcat连接了2个字符串。但是在运行时显示分段错误(核心已转储)。

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

void main()
{
    FILE *fptr;
    char *data="867330029590851,144311,140817,130294,0801536,15,00,-1380021593,,N,,,,,180717034311,,,,,4.18,,,,,,,,NA";
    char *timeStamp="14-08-17,14:45:38";

    char *currentTimeStamp=strcat(data,timeStamp);


    /*  open for writing */
    fptr = fopen("RedisData.txt", "w");

    if (fptr == NULL)
    {
        printf("File does not exists \n");
        return;
    }
    // printf("string \n");
    // scanf("%s", data);

    printf("%s\n",currentTimeStamp);

    fprintf(fptr,"currentTimeStamp= %s\n",currentTimeStamp);


    fprintf(fptr, "Data    = %s\n", data);
    fprintf(fptr, "TimeStamp     = %s\n", timeStamp);
    fclose(fptr);
}

最佳答案

data是字符串文字,任何对其进行修改的尝试都会调用未定义的行为。

另一方面,使用strcat时,目标数组中必须有足够的空间来容纳源字符串。

char *data="867330029590851,144311,140817,130294,0801536,15,00,-1380021593,,N,,,,,180717034311,,,,,4.18,,,,,,,,NA";
char *timeStamp="14-08-17,14:45:38";
char *currentTimeStamp = malloc(strlen(data) + strlen(timeStamp) + 1);
strcat(currentTimeStamp, data);
strcat(currentTimeStamp, timeStamp);

关于c - 我在文件操作中使用strcat时如何解决段错误(核心转储),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45707204/

10-10 06:03