2d arrays with pointers [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have the following code so far:
#include <stdio.h>
int foo (int *pointer, int row, int col);
int main() {
int array[3][3] ={ {1,2,3},{4,5,6},{7,8,9}};
int *pointer= array[0];
int row = 2;
int col = 2;
int answer = foo (pointer, row, col);
printf("%d", answer); //prints 5 (which is wrong)
printf("%d", array[2][2]); //prints 9
}
int foo (int *pointer, int row, int col){ //I don't want to use any square brackets here, unless I really have to.
int value;
value = *((int *)(pointer+row)+col);
return value;
}
So my main issue is with passing a 2D pointer, please explain in detail as I am still new at coding. I don't want to really change what I am passing (as in I want to use the pointer in foo(pointer, row, col) and not foo (array, row, col).

passing a 2D pointer
From how you (ab)used the terminology, it's quite clear that you're under the wrong impression that pointers and arrays are the same. They aren't.
If you want to access a multidimensional array using pointers, you must specify all its dimensions (except the first, innermost one) and use pointer arithmetic correctly, possibly using pointers-to-array, since multidimensional arrays are contiguous in memory:
const size_t h = 2;
const size_t w = 3;
int arr[h][w] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int *p = &arr[1][2];
int *q = arr[1];
int (*t)[3] = &arr[1];
printf("arr[1][2] == %d == %d == %d\n", *p, q[2], (*t)[2]);
return 0;

int *pointer= array[0];
Instead of use this
int *pointer= &array[0];
Or
int *pointer= array;

Related

Why did the array lose the last element when passed into another function? [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 1 year ago.
I made an static int arr[3] and set to 1, 2, 3.
I can print 1, 2, 3 in the same function.
But when I pass the array it only prints 1, 2.
Why? What happened? How do I fix this?
#include <stdio.h>
void printArray(int* arr){
size_t n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){
printf("%d\n",arr[i]);
}
}
int* makearray()
{
static int arr[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
printf("The Array before passing onto stack\n");
size_t n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){ printf("%d\n",arr[i]);}
printf("\nThe Array when attempting to pass to another function\n");
printArray(arr);
return arr;
}
int main(void) {
int* m = makearray();
return 0;
}
By converting your array to a pointer, you removed the information that sizeof needs to know its total length.
Instead, it just gives you the size of a single int *, which is twice the size of a single int on your machine.
Hence, you only see the first two elements.
In C, you're basically forced to pass around the length alongside the pointer. You can wrap the two in a struct to make it easier to use, but don't expect the niceties of other languages you may be used to.

Why cant we initialise an array with the help of other array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include<stdio.h>
int main() {
int i,j;
int a[3][3]={1,2,3,4,5,6};
int b[3][3]=a[3][3];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("%d",b[i][j]);
}
// Why can't we initialize array like this
Why can't I initialize the array with the help of array
here why I can't initialize the array with the help of array
You can, just not with the syntax you are using. Here are a few options:
#include<stdio.h>
#include<string.h>
int
main(void)
{
int i,j;
int a[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int *b[3] = { a[0], a[1], a[2] };
int c[3][3];
int (*d)[3] = a;
memcpy(c, a, sizeof a);
for( i = 0; i < 3; i++ ){
for( j = 0; j < 3; j++ ){
printf("%d %d %d\n", b[i][j], c[i][j], d[i][j]);
}
}
return 0;
}
You declare int a[3][3]. Then try to initialize int b[3][3] = a[3][3]; but a[3][3] is out of bounds on the right hand side. If you mean the single element a[2][2], then can do { [0] = a[2][2] } if that is what you want. c17, as far as I can tell, does not support array initialization from another array, i.e. use memcpy.
In C, initializing or assigning a multidimensional array like that will throw invalid initializer as you wanted to initialize b with a.
int a[3][3]={1,2,3,4,5,6,7,8,9};
int b[3][3];
memcpy (b, a, 3*3*sizeof(int));
C is not a high level language. It doesn't copy strings / multidimensional arrays when you're assigning. In C, assignment operator will always have complexity O(1). What you can do is working with the memory addresses.

Subtracting arrays with different size in c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
void function(int first[], int second[], int third[]) {
int i;
for(i=0;i<64;i++) {
third[i] = first[i] - second[i];
}
}
I want to subtract the second array from the first one. The first one contains 32 numbers and the second one has 13 numbers. It works fine for the first 13 numbers. Once the second array "runs out" of elements, I want to use the numbers from the beginning of the second array. So I want to subtract the second array's first element from the 14th element of the first one, and so on... How could I achieve it?
you can use % to get the remainder of the index from length of the array, this way, you can iterate through the second array in a circular way!
I changed your code to do as you asked for
// get the length of array before you pass it to the function like this:
// int second_len = sizeof(second) / sizeof(second[0]);
void function(int first[], int second[], int third[], int second_len) {
int i;
for(i=0;i<64;i++) {
third[i] = first[i] - second[i % second_len];
}
}
The elements of the first and second array are sequences of positive
numbers and they are both closed with -1
You could just do as below.
Maintain two indexes i and j.
Where i will index larger array and j will index smaller array and once smaller array reaches -1 reset the j to 0 and once larger array reaches -1 break the loop.
void function(int first[], int second[], int third[]) {
int i =0,j=0;
for(i=0; i<64 ; i++;j++) {
if(second[j] == -1)
{
j =0; //Reset the j=0 to start from beginning
}
if (first[i] == -1)
{
third[i] = -1; //Terminate third with -1
break; //Break the loop
}
third[i] = first[i] - second[j];
}
}
One option is to add an additional looping variable:
void function(int first[], int second[], int third[],
int first_size, int second_size)
{
int i=0, k=0;
for(i=0; i<first_size; i++) {
third[i] = first[i] - second[k];
k++;
if (k==second_size)
k = 0;
}
}
i tracks the size of the first array and the output like in your program, and k follows the size of the second array and resets whenever the size is reached. Instead of hardcoded array sizes the function now takes two additional arguments: sizes of the first and second arrays.
For future reference, the rest of this code could look like this:
#include <stdio.h>
void print_array(int arr[], int);
void function(int arr_1[], int arr_2[], int arr_3[], int, int);
int main()
{
int arr_1[] = {1,2,3,4,5};
int arr_2[] = {1,2};
int n_1 = sizeof(arr_1)/sizeof(arr_1[0]);
int n_2 = sizeof(arr_2)/sizeof(arr_2[0]);
int arr_out[n_1];
function(arr_1, arr_2, arr_out, n_1, n_2);
print_array(arr_1, n_1);
print_array(arr_2, n_2);
print_array(arr_out, n_1);
return 0;
}
void print_array(int arr[], int n_elem)
{
int i = 0;
for (i=0; i<n_elem; i++)
printf("%d ", arr[i]);
printf("\n");
}
With print_array as a function to avoid repeating the same lines of code for each print.
For the example input, the output will be 0 0 2 2 4.

Write a program that swaps values within an array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is for homework
Here is my program
#include <stdio.h>
void swap (int *a , int *b , int *c , int *d , int *e ) {
int temp1 = a;
a = b;
b = temp1;
int temp2 = b;
c = d;
d = temp2;
int temp3 = e
e = a;
a = temp3;
}
void swap (int *a , int *b , int *c , int *d , int *e );
int main(void)
{
int arr[15] = {0};
int i;
int a = arr[0], b = arr[7], c = arr[8], d = arr[3], e = arr[14];
printf("Enter 15 integers\n");
for(i = 0; i < 15; ++i) {
scanf("%d" , &arr[i]);
//printf("The ints are %d " , arr[i]); checked if all the ints were recorded
}
swap(a, b, c, d, e);
printf("Swapped array:\n %d" , arr[i]);
return 0;
}
So The program is asking me to have the user enter 15 integers. The function would have to swap the 1st integer entered (arr[0]) with the seventh integer entered (arr[7]). Then swap the 8th with the 3rd, then swap the last one with the first. My program complies but gives a handful of warnings and when I try to print my swapped array, all I get is a value of 0. Any help would be appreciated!
Edit
Sorry I heard from someone to not worry about the warnings- counter-intuitive to listen. The warnings are:
[In the function]
assignment makes pointer from integer without a cast
initialization makes integer from pointer without a cast
In main
passing argument [numbers] of swap makes pointer from integer without a cast
There's several problems with your code.
First, the swap function doesn't work. You're swapping the values of the pointers that are local variables inside the function, you're not swapping the array elements they point to. You need to indirect through pointers to get the values.
int temp1 = *a;
*a = *b;
*b = temp1;
And similar for all the other pairs you're swapping.
Second, swap expects pointers as arguments, but you're passing int variables from main(). You need to use pointer variables, which you set to the addresses of the array elements:
int *a = &arr[0], *b = &arr[7], *c = &arr[8], *d = &arr[3], *e = &arr[14];
You might consider changing the swap() function so it just takes two pointers, and call it 3 times to do all 3 swaps.
Finally, to print the array, you need to print the elements in a loop:
printf("Swapped array: ");
for (i = 0; i < 15; i++) {
printf("%d ", arr[i]);
}
printf("\n");

Query related to Pointers and Arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The questions from my textbook is:
Write a function that returns a pointer to float and has two parameters: 1)a two dim array of floats with COL column and 2)an integer that represents the number of rows. Returned pointer should point to an array of floats containing the sum of the elements in the corresponding row of the 2 dim array.
My solution is:
float* ptr (float array[][COL], int rows) {
float *ptr;
int j;
for (j=0; j<COL; j++)
*ptr += array[rows][j];
return *ptr;
}
I just wonder whether this solution is correct? Thank you very much.
You've not allocated any memory for ptr to point at, so the answer is unavoidably wrong. You have to ensure that the memory will last long enough to be usable, so you can't return a pointer to an automatic array; you'll either have to have a static array (but how do you make it big enough), or you'll have to dynamically allocate the memory (malloc() et al) and then make sure the calling code frees what was allocated.
You also have algorithmic problems. You're accumulating all the values for all rows into a single value, whereas you're requested to calculate a separate value for each row.
Also, *ptr is a float; you'd need just return ptr; to have the types correct.
Your function name needs to be different, too.
#include <stdio.h>
#include <stdlib.h>
enum { COL = 7 };
float *row_sums(float array[][COL], int rows)
{
float *ptr = malloc(rows * sizeof(*ptr));
if (ptr != 0)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < COL; j++)
ptr[i] += array[i][j];
}
return ptr;
}
int main(void)
{
float data[][COL] = { { 1.0 }, { 2.0 }, { 0.0, 3.0 }, { -1.0, -2.0 } };
float *result = row_sums(data, 4);
for (int i = 0; i < 4; i++)
printf("%d: %.1f\n", i, result[i]);
free(result);
return(0);
}
The use of 4 is sub-optimal; it should be something like ROWS, where that's defined using:
enum { ROWS = sizeof(data) / sizeof(data[0]) } ;

Resources