c - 在指向 char 的指针数组中输入单词时出错

标签 c arrays pointers

该程序检查指向 char **s 的指针数组中的单词(您应该首先加载)是否与函数 fun 中的单词相同。由于某种原因,我无法在 main 函数中正确加载单词,而且我不知道原因在哪里。

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

int fun(char **s,int j)
{
    int i, num=0;

    for(i=0;i<j;i++)
    {
       if(strcmp(s[i],"first")==0)
        num++;
        if(strcmp(s[i],"second")==0)
         num++;

    }

    if(num==j)
      return 1;
    else
      return 0;

}
int main(int argc,char *argv[])
{
    char **s=(char**)malloc(20*sizeof(char*)); // alloc
    char ss[20];
    int i=0,ret;

    while(1)  // while string 'ss' is different from string "stop"
    {
       scanf("%s",ss);

       if(strcmp(ss,"stop")==0)
        break;
       else
     {    s[i]=ss; // if ss is different from "stop"
          i++;

     }

}

ret=fun(s,i); // returns 1 if words are the same as words in function fun

if(ret)
 printf("Matching\n");

else
 printf("Doesn't matches\n");

for(int t=0;t<i;t++)
   free(s[i]);
free(s);    

}

最佳答案

char **s=(char**)malloc(20*sizeof(char*)); // alloc

这为 20 个指向 char 的指针腾出了空间。它没有腾出任何空间来实际存储 char

s[i]=ss; // if ss is different from "stop"

在循环中执行此操作只会产生一堆指向相同底层 char 序列的指针。您需要使用循环或类似 strncpy 的函数实际复制char

for(int t=0;t<i;t++)
   free(s[i]);

这应该是一个明显的错误迹象,因为没有与此 free 对应的 malloc。 (您唯一的 malloc 与下面的 free(s); 相对应。)

关于c - 在指向 char 的指针数组中输入单词时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52807496/

相关文章:

c - 如何将函数的返回值存储到C中的数组中

c++ - 在 C++ 中的指针数组中,内存过度使用是否会导致指针存储在非连续的内存块中?

c - 为什么char指针签名后可以增值?

c - 更安全的重新分配方式

c - SIMD (AVX) 比较

javascript - 拉维 |如何在 JavaScript 中访问 session 数组?

c - 结构新手,为什么我的程序没有运行?

C - 从特定的大范围中获取素数

c - 函数更改指针参数,但调用方看不到更改

php - 如何在PHP中生成大量 session ID?