简体   繁体   English

如何在C中向数组添加元素?

[英]How do I add elements to an array in C?

What I'm trying to do is find a way to add extra elements to the already hardcoded int array matrix.我想要做的是找到一种向已经硬编码的 int 数组矩阵添加额外元素的方法。 Here is my current code:这是我当前的代码:

#include <stdio.h>

int main(){

    int matrix[25] = {2,3};
    int i;
    int j;

    for(i=4,j=2; i<21 && j<17; i++,j++){
        matrix[j] = i;
    }
    printf("%d", matrix);
}

I'm not sure what went wrong here.我不确定这里出了什么问题。

You can't print array elements with integer type specifier %d .您不能使用整数类型说明符%d打印数组元素。 You need to iterate through the array elements using a loop such as for and then print each element.您需要使用诸如for的循环遍历数组元素,然后打印每个元素。

for(int x=0; x < 17; x++) {
   printf("%d", matrix[x]);
}

You are giving to print directly matrix but it will show a warning like this您正在直接打印矩阵,但它会显示这样的警告

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]

this is because when you give only matrix without indexes([]) or '*' it prints garbage value so you can use loops for printing a matrix这是因为当你只给出没有索引 ([]) 或 '*' 的矩阵时,它会打印垃圾值,所以你可以使用循环来打印矩阵

for(int i=0; i < 17; i++)
   printf("%d", matrix[i]);

OR或者

for(int i=0; i < 17; i++) 
   printf("%d ", *(matrix+i));

Peace!和平!

Happy Coding!快乐编码!

    int main() 
{ 
    int r = 3, c = 4; 
    int *arr = (int *)malloc(r * c * sizeof(int)); 

    int i, j, count = 0; 
    for (i = 0; i <  r; i++) *emphasized text*
      for (j = 0; j < c; j++) 
         *(arr + i*c + j) = ++count; 

    for (i = 0; i <  r; i++) 
      for (j = 0; j < c; j++) 
         printf("%d ", *(arr + i*c + j)); 

Use can use malloc to to create dynamic array.使用可以使用 malloc 来创建动态数组。 by using the malloc if the size of the array is full you can reallocate the array by using the malloc function.通过使用 malloc 如果数组的大小已满,您可以使用 malloc 函数重新分配数组。 The malloc will copy the previous array in the new array with the new size. malloc 将使用新大小复制新数组中的前一个数组。

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

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