简体   繁体   中英

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. 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 . You need to iterate through the array elements using a loop such as for and then print each element.

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. by using the malloc if the size of the array is full you can reallocate the array by using the malloc function. The malloc will copy the previous array in the new array with the new size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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