指向char的指针数组和指向int的指针数组之间的区别 [英] Difference between array of pointers to char and array of pointers to int

查看:127
本文介绍了指向char的指针数组和指向int的指针数组之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个C问题:

我不明白为什么此代码有效:

I dont understand why this code works:

char *c[] = {"hello","world"};

但这不是:

int *v[] = {{1,2},{3,4}};

对我来说,它们是同一件事(使用各自类型初始化的指针数组),但显然不是.那么到底有什么区别呢?谢谢.

For me they are the same thing (array of pointers initialized with their respective type) but clearly they are not. What is exaclty the difference then? Thanx.

如果对我的帖子投反对票的人会说为什么,这是一个不好的问题……那将是很好的事情.

If the person who downvoted my post could say WHY this is a bad question... that would be great.

推荐答案

假设您在谈论C,不同之处在于:

Assuming you are talking about C, the differences are:

  • "hello"定义字符数组
  • 数组可以衰减到指针
  • "hello" defines an array of characters
  • arrays can decay to pointers

但是:

  • {1,2}未定义int s的数组.它指定了一个值列表,可用作int类型(或可转换)的字段的初始化程序.
  • {1,2} does not define an array of ints. It specifies a list of values which can be used as initializers to fields of type int (or convertible).

int的类似情况是使用复合数组文字:

The analogous case for the int would be to use a compound array literal:

int *v[] = { (int[]){1,2}, (int[]){3,4} };

复合文字默认情况下是可写的(与字符串文字不同),因此您可以使用v[0][0] = 5;,而对于char版本则不能.

Compound literals default to being writable (unlike string literals), so you can then go v[0][0] = 5;, which you cannot do with the char version.

这篇关于指向char的指针数组和指向int的指针数组之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆