【问题标题】:passing mixed const integer ASCII values and const char array in C and passing const int without previous declaration [duplicate]在 C 中传递混合的 const 整数 ASCII 值和 const char 数组,并在没有先前声明的情况下传递 const int [重复]
【发布时间】:2020-04-05 21:00:25
【问题描述】:

我对这个问题有 2 个部分。

1:如果我想将 const int 数组传递给函数,通常我会这样做。

const int array[3] = {1,2,3};
somefunction(array,3);

但我想用一种更简单的方式来做,就像你可以用字符串做的那样,这可能吗?

somefunction("abc",3);

对于somefunction({1,2,3},3); 之类的东西,我知道这行不通,但有没有语法正确的方法来做到这一点。

2:如果上一个问题是可能的,那么这个问题就被回答了。有没有办法在 const 字符串中混合 ascii 值。像... somefunction({1,2,3,"test"},7); 我知道这行不通,但有没有语法正确的方法来做到这一点。

【问题讨论】:

  • 以上重复的帖子是针对第一个问题的。我相信第二个的答案是否定的,它做不到。 C 中的数组不能有不同类型的元素。

标签: arrays c constants ascii string-literals


【解决方案1】:

回答你的第一个问题我可以说你可以使用复合文字来做到这一点。例如

#include <stdio.h>

void f( const int a[], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );
}

int main(void) 
{
    f( ( int[] ) { 1, 2, 3 }, 3 );
}

但是你不能有一个包含不同类型元素的数组。

因此对于{1,2,3,"test"} 这样的构造,您需要将字符串文字拆分为单独的字符,例如{1,2,3, 't', 'e', 's', 't'}

【讨论】:

  • 非常感谢我的想法是这样的( char[] ) { 1, 2, 'a' }
猜你喜欢
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
相关资源
最近更新 更多