私はいくつかの問題を引き起こしている非常に簡単な機能を持っています。私がしたいのは、文字列から変更した後に部分文字列を返すことだけです。しかし、コードを実行すると、セグメンテーション違反が発生します。私のコードで何が起こっているのですか:
#include <stdio.h>
#include <string.h>
const char *new_name(char str[])
{
char * pch;
char * last="";
char * pch2;
static char name[80];
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,"/");
while (pch != NULL)
{
last=pch;
pch = strtok (NULL, "/");
}
pch2 = strtok (last,".");
strcpy(name, pch2);
strcat(name, ".ppm");
return name;
}
int main()
{
printf("New name: %s",new_name("/home/test/segmentation/test.pgm"));
return 0;
}
編集: 別の質問があります: この関数の戻り値を別の関数の入力として使用したいのですが、char を受け入れ、返される値は const char です。変換方法は?