Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在分配的数组中搜索字符串(c)_C - Fatal编程技术网

在分配的数组中搜索字符串(c)

在分配的数组中搜索字符串(c),c,C,我想在指针中存储的数组中查找字符串。我已经尝试了以下方法: #include <stdio.h> #include <malloc.h> #include <stdlib.h> int main() { int n,i; char (*ptr)[50]; char search[50]; printf("How many students?\n"); scanf("%d",&n); for(i=0;i<n;i++){ printf("En

我想在指针中存储的数组中查找字符串。我已经尝试了以下方法:

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int main() {
int n,i;
char (*ptr)[50];
char search[50];
printf("How many students?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
    printf("Enter the name of student:\n");
    scanf("%49s", ptr[i]);
}
printf("Enter a name to search:\n");
scanf("%49s",search);
for (i=0;i<n;i++){
    printf(strcmp(ptr[i],search));

}
}
但我看到了这个错误:

[警告]传递'printf'的参数1会使指针从整数变为不带强制转换的整数

首先,strcmp返回整数notaddresssee。替换printfstrcmpptr[i],搜索; 应该是 printf%d\n,strcmptr[i],搜索

第二,char*ptr[50];是指向数组的指针,其指向的位置是什么?它是不必要的,最好你可以采取数组指针字符*ptr[50]


您想要打印什么?strcmp返回一个整数-您需要使用整数格式打印。ptr是指向50个字符数组的指针。它没有初始化,也没有指向读取学生姓名所需的足够内存。@medalib我想打印字符串是否存在于数组中。对不起,我没有在代码中显示它。我只想在数组中找到字符串。如果学生人数大于50,您希望发生什么情况?请记住释放
char *ptr[50];/* array of 50 char ptr */
for(i=0;i<n;i++){
      ptr[i] = malloc(size); /* allocate memory for each char buf, define size */
      printf("Enter the name of student:\n");
      scanf("%49s", ptr[i]);
}
for (i=0;i<n;i++){
     //printf("%d\n",strcmp(ptr[i],search));
     if(strcmp(ptr[i],search) == 0) {
       printf("%s exists \n",search);
     }
}
for(int i =0 ;i < n;i++) {
   free(ptr[i]);
}