简体   繁体   English

指向C中的char和character数组的指针

[英]Pointer to char and character array in C

I'm always wondering what is the difference between those two in C 我一直想知道这两个在C语言之间有什么区别

char *str;
char str[50];

I have the following code used to read string from user input instead of using gets. 我有以下代码用于从用户输入中读取字符串,而不是使用gets。

int read_line(char *str, int n);

int main (int *argc, char *argv[])
{
  char *str;

  read_line(str, 50);
  printf("%s", str);
  return 0;
}

int read_line(char *str, int n)
{
  int ch, i = 0;

  while((ch = getchar()) != '\n')
  {
    if(i < n)
    {
        *str++ = ch;
        i++;
    }
}
*str = '\0';

return i;
}

The compilation works fine as expected but get crashed when I tried to run. 编译工作正常,但在尝试运行时崩溃了。 And then I change the argument to the read_line() function, instead of char *str i use char str[50] . 然后将参数更改为read_line()函数,而不是char *str我使用char str[50]

The program runs as expected when using char *str[50] as argument. 使用char *str[50]作为参数时,程序将按预期运行。

can someone explain why this happens? 有人可以解释为什么会这样吗? or what is the main difference of pointer to char and character array ? pointer to charcharacter arraypointer to char的主要区别是什么?

Array ids more or less work like pointers. 数组ID或多或少像指针一样工作。

But with pointers you always need to do 3 steps manually: 但是使用指针,您始终需要手动执行3个步骤:

  • create the pointer 创建指针
  • allocate memory to point to 分配内存以指向
  • initialize the pointer to point there 初始化指针以指向那里

char str[50]; does all three, while char *str; 三个都做,而char *str; only creates an uninitialized pointer, and you don't even create a buffer to point to. 只创建一个未初始化的指针,甚至不创建指向的缓冲区。

Further differences between pointers and array ids: 指针和数组ID之间的进一步区别:

  • an array id represents the array's address in compile time only, while the pointer stores an address in memory, and you might even change it. 数组ID仅在编译时表示数组的地址,而指针将地址存储在内存中,您甚至可以更改它。
  • sizeof array returns the array size, while sizeof ptr returns the size of memory needed to store an address. sizeof array返回数组大小,而sizeof ptr返回存储地址所需的内存大小。

主要区别在于,后者为50个字符分配内存(str是第一个元素的指针),而前者仅声明一个指针(除了指针变量本身的内存之外,没有分配内存)。

The difference will be seen at once if you will run this simple program 如果您运行此简单程序,将立即看到区别

#include <stdio.h>

int main( void )
{
    char *str1;
    char str2[50];

    printf( "%zu\n", sizeof( str1 ) );
    printf( "%zu\n", sizeof( str2 ) );
}

The program output might look like 程序输出可能看起来像

4
50

As you see the array str2 has enough memory to store a string up to 50 characters while the pointer can store only an address of some memory. 如您所见,数组str2有足够的内存来存储最多50个字符的字符串,而指针只能存储某些内存的地址。

When you pass an array to a function as in your code 当您像代码中那样将数组传递给函数时

read_line(str2, 50);

(where str2 declared like char str2[50]; ) then the array name is implicitly converted to pointer to its first element. (其中str2声明为char str2[50]; ),然后将数组名称隐式转换为指向其第一个元素的指针。 Thus for example these function declarations are equivalent 因此,例如,这些函数声明是等效的

int read_line(char *str, int n);
int read_line(char str[50], int n);

or even like 甚至喜欢

int read_line(char str[100], int n);
int read_line(char str[], int n);

and declare the same one function because the parameter declared like array is adjusted to pointer. 并声明相同的一个函数,因为像数组这样声明的参数已调整为指针。

So when you pass the array the function gets pointer to the first element of the array for which the memory is already allocated because the array was defined. 因此,当您传递数组时,该函数将获得指向已定义内存的数组的第一个元素的指针,因为已定义了数组。

When you pass the pointer as you did in this main function 当您像在此主函数中一样传递指针时

int main (int *argc, char *argv[])
{
  char *str;

  read_line(str, 50);
  printf("%s", str);
  return 0;
}

then it was not initialized and has some indertermined value. 则它没有被初始化并且具有一些不确定的值。 As result the program behaviour is undefined. 结果,程序行为是不确定的。 The pointer shall point to some allocated memory where input data can be stored. 指针应指向一些分配的存储器,可以在其中存储输入数据。

For example you can do this the following ways 例如,您可以通过以下方式执行此操作

int main (int *argc, char *argv[])
{
  char *str1;
  char str2[50];

  str1 = str2;

  read_line(str1, 50);
  printf("%s", str1);

  return 0;
}

or 要么

int main (int *argc, char *argv[])
{
  char *str = malloc( 50 * sizeof( char ) );

  read_line(str, 50);
  printf("%s", str);

  free( str );

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM