C 使用字符串和 SEGFAULT

标签 c pointers segmentation-fault

你好,抱歉我的英语不好。
我是从C语言开始的,但是我没有得到很好的指导......
我搜索了类似的主题,但没有从他们那里得到,所以我创建了自己的主题。
我有 main 函数,我在其中调用函数 newSpeak。
有我的 newSpeak 代码,但还没有全部...

char * newSpeak ( const char * text, const char * (*replace)[2] )
{
int i;
char * alpha;
for(i=0;i<4;i++)
    {
        alpha=strstr(text, replace[0][4]);
        if(alpha[0])
            strncpy (alpha,replace[1][0],10);   
    }
return 0;


谢谢回答 编辑:我找到了问题的根源。 它有效,当我不使用循环并运行一次时。但是即使 for 循环中的条件是 i<1 它也不起作用,这应该让它只运行一次......这对我来说很奇怪......

最佳答案

    alpha=strstr(text, replace[0][4]);
    if(alpha[0])
        // looks crashy

男人 strstr:

These functions return a pointer to the beginning of the substring, or NULL if the substring is not found.

编辑:

很难说出您要做什么,但可以在下面找到对您的代码进行的任意改编。如果这是我的程序,我会写得非常不同。我提到这一点是因为我不希望有人读到这篇文章并认为这是应该做的。

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

void newSpeak (char *text, const char *replace[4][2])
{
  int i, j;
  char *alpha;
  for (i = 0; i < 4; i++) {
    if (alpha = strstr(text, replace[i][0])) {
      for (j = 0; alpha[j] && replace[i][1][j]; j++)
        alpha[j] = replace[i][1][j];
    }
  }
}

int main ()
{
  char buf[100] = "abc";
  const char *replace[4][2] = {
    { "a", "e" },
    { "b", "f" },
    { "c", "g" },
    { "d", "h" },
  }; 
  newSpeak(buf, replace);
  puts(buf);
}

关于C 使用字符串和 SEGFAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364584/

相关文章:

c - 未分配的字符串如何存储在内存中以及如何引用它?

C 编程、堆栈、打印堆栈错误

char** 分配以及如何存储值

python - 使用 Python 帮助抛出 SEGFAULT

c++ - 如何为手机构建 slider 拼图软件

c - 头文件中缓冲区分配的可能性

c - 传递数组指针并打印

c - 指向循环结构体的指针数组

c - 如何将 char* 设置为 char*?

c - tcp 服务器客户端通信 read() write() 问题。 c语言