Reputation: 362
I want to find a string in an array stored in a pointer.I already tried this way:
#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));
}
}
But I see this error:
[Warning] passing argument 1 of 'printf' makes pointer from integer without a cast
Upvotes: 0
Views: 71
Reputation: 11931
Firstly, strcmp
returns integer
not address(see https://linux.die.net/man/3/strcmp). Replace printf(strcmp(ptr[i],search));
should be
printf("%d\n",strcmp(ptr[i],search));
Secondly, char (*ptr)[50];
is pointer to an array, where its pointing ? Its unnecessary, better you can take array of pointer char *ptr[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]);
}
And
for (i=0;i<n;i++){
//printf("%d\n",strcmp(ptr[i],search));
if(strcmp(ptr[i],search) == 0) {
printf("%s exists \n",search);
}
}
Also once job is done don't forget to free
the dynamically allocated memory for each array of char pointer by calling free()
. Something like this
for(int i =0 ;i < n;i++) {
free(ptr[i]);
}
Upvotes: 1