问题
i'd like to know why this code works fine with char tab[100]
but doesn't work if I use char *tab
? fgets function takes a char*
array as a parameter right ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Int Palindrome(char* str, int i, int j);
int main()
{
char tab[100];
printf("Enter your string : \n");
fgets(tab, 100, stdin);
int j = strlen(tab);
printf("%d\n", Palindrome(tab, 0, j - 2));
return 0;
}
int Palindrome(char* str, int i, int j)
{
if (i >= j)
{
printf("My word is a Palindrome !\n");
return printf("<(^w^)>\n");
}
else if (str[i] != str[j])
{
printf("My word is not a Palindrome !\n");
return printf("<(X.X)>\n");
}
else
{
return Palindrome(str, i + 1, j - 1);
}
}
回答1:
With "not work" you probably mean you get some serious error reported like a segmentation fault.
The difference between char tab[100]
and char *tab
is that the first has storage allocated and the second hasn't. When you call a function with an array as a parameter, then the compiler passes a pointer to the first element of the array, so for the function that got called it doesn't see the difference whether it is called with an array-parameter or with a pointer-parameter.
So to let your program work with char *tab;
you must first allocate storage to this pointer, such as with char *tab=malloc(100);
Now that there is valid storage allocated (and the pointer now points to it), you can call your function with this tab
as parameter.
来源:https://stackoverflow.com/questions/45162908/difference-between-char-array100-and-char-array-when-calling-functions