调用函数时char array [100]和char * array之间的区别? [英] Difference between char array[100] and char *array when calling functions?
问题描述
我想知道为什么此代码在char tab[100]
上可以正常使用,但是如果我使用char *tab
则不起作用? fgets函数将char*
数组作为参数正确吗?
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);
}
}
推荐答案
对于无效",您可能表示您报告了一些严重错误,例如分段错误.
With "not work" you probably mean you get some serious error reported like a segmentation fault.
char tab[100]
和char *tab
之间的区别在于,第一个已分配存储,第二个未分配存储.当您使用数组作为参数调用函数时,编译器会将指针传递给数组的第一个元素,因此对于被调用的函数,无论是使用数组参数还是使用数组参数,都看不到区别.带有指针参数.
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.
因此,要让您的程序与char *tab;
一起使用,必须首先为该指针分配存储空间,例如与char *tab=malloc(100);
一起使用.既然已分配了有效的存储空间(并且指针现在指向它),则可以调用函数将此tab
作为参数.
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.
这篇关于调用函数时char array [100]和char * array之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!