我的代码中 strncpy 中查找并打印最长单词的编译错误

标签 c arrays string function strncpy

我编写了一个程序来查找最长的单词并打印它。

我的代码是:

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

int MaxWord(char text[],char[]);

int main (void){
  char text[1000];
  char word[1000];
  int max;

  printf("geben Sie den Text bitte : ");
  gets(text);
  max=MaxWord(text,word);
  printf("ist mit %d Zeichen das laengste wort im Text\n\n\n",max);
  return 0;
}
int MaxWord(char text[], char word[])
{
  char i;
  int ctr=0;
  int max=0;
  int len;
  char begin=0;

  len=strlen(text);
  for(i=0;i<len+1;i++)
  {
    if(isalpha(text[i]))
    {
        if(ctr==0)
        {
            begin=i;
        }
        ctr++;
    }
    else 
    {

        if(ctr>max)
        {
            max=ctr;

        }

        ctr=0;
    }
 }
 strncpy(word,begin,max);
 printf("%s ",word);
 return max;
}   

错误是:

error #2140: Type error in argument 2 to 'strncpy'; expected 'const char * restrict' but found 'char'.

我该如何解决这个问题?

最佳答案

首先,您不应该使用 gets() 函数。使用 scanf 代替。 另请参阅 http://www.cplusplus.com/reference/cstring/strncpy/

函数 strncpy 需要一个 const char* (以便您确信该函数不会修改源字符串)并且您向它传递一个字符。因此出现了错误。请修改您的函数以传入 char 指针。

您需要重新检查逻辑并通过传入正确的源字符串来修复 strncpy 调用。

关于我的代码中 strncpy 中查找并打印最长单词的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029894/

相关文章:

c++ - O(log n) 中的广度优先搜索

为 ARM11 交叉编译 GStreamer、Airstream

c - 为什么我需要从 1 << 64 中减去二得到 2^64 - 1?

c# - 从字符串数组创建更大的字符串

c - 使用C删除非空目录时出现段错误

java - 在嵌套循环中填充数组

ios - 从通知对象传递数组会导致 iOS 10 中的应用程序崩溃

C# 可以将字符串格式存储在变量中吗?

r - 从 R 中的字符串中提取最后 n 个字符

c - 将受污染的变量传递给受污染的接收器