I'm sending array to function frekvens_of_array and the size of it. Problems is it keeps telling me that I can't compare a pointer and an int. I try to insert new unique number into frekvens and add 1+ to hit every time number comes up in alanyzed_array
When I build this program, I'm getting errors and warnings like those below.
if(frekvens[j] != analyzed_arr[i])
warning: comparision between pointer and integer [enable by default]
frekvens[j] = analyzed_arr[i]; error: incompatible types when assaigning to type 'int[1]' from type 'int'
int frekvens_of_array(int analyzed_arr[100], int array_size){
int frekvens[100][1];
int i = 0;
int j = 0;
int n = 0;
int hit = 0;
for(i = 0; i < array_size; i++){
if(frekvens[j] != analyzed_arr[i]){
frekvens[j] = analyzed_arr[i];
for(n = 0; n < array_size; n++){
if(frekvens[j] == analyzed_arr[n]){
hit++;
}
}
frekvens[j][0] = hit;
j++;
}
}
return 0;
}
int main(void){
int ange_tal_array[100];
int array_size = 100;
frekvens_of_array(ange_tal_array, array_size);
return 0;
}
Sorry I realized that I have misunderstandings of your code. The right way to solve your problem is to change the declaration of frekvens from:
int frekvens[100][1];
to:
int *frekvens[100];
to make it an array of pointers. And other parts of your code don't need to be modified.
int frekvens[100][1];
This is a 2D array of 100 rows and 1 columns. Quite frankly, having only one column doesn't make any sense; you should just turn it into a 1D array.
The issue is here:
if(frekvens[j] != analyzed_arr[i])
You're only indexing half of your 2D array. frekvens[j] is of type int[1], so it's still an array. You're then comparing to an integer, which doesn't work.
The easiest fix would be to rewrite the line as if(frekvens[j][0] != analyzed_arr[i]), but the better solution would be to convert frekvens to a 1D array instead.
Related
#include <stdio.h>
int sumofArrayNum(int numList[]);
int main(){
int result,numList[]={23,32,54,23,54,32,3,35};
result = sumofArrayNum(numList);
printf("sum= %d", result);
return 0;
}
int sumofArrayNum(int numList[]){
int sum = 0;
for(int i = 0; i < 10; ++i){
sum += numList[i];
}
return sum;
}
Output is different each time I build and run it.
E.g. output is sum = 1032918821
Expected output I would like is sum = 256
Parameters like int numList[] is the same as int* numList, compiler will not know elements count of it if it was not explicitly defined. By the way, int numList[8] is also the same as int* numList. C language does not check the range of array.
There are some ways to get and check the array size.
size/count parameter
int sumofArrayNum(int numList[], int listSize){
int sum = 0;
for(int i = 0; i < listSize; ++i){
sum += numList[i];
}
return sum;
}
Here listSize should be the count of elements.
And you can use macro to hide the count parameter:
#define sumofArray(array) sumofArrayNum((array), sizeof(array)/sizeof(*array))
point to the whole array
int sumofArrayNum(int (*numList)[8]){
int sum = 0;
for(int i = 0; i < sizeof(*numList)/sizeof(**numList); ++i){
sum += (*numList)[i];
}
return sum;
}
Call it by sending pointer of array:
result = sumofArrayNum(&numList);
Compiler(such as gcc) can do a weak check for this: give a warning if you send an array which are not int (*)[8].
Note that you have to ensure validity of array, and array size must be constant.
Besides,
Output is different each time I build and run it.
It is because only 8 elements has been defined, index range is 0〜7. numList[8] and numList[9] is undefined, mean any value is possible. Maybe used, changed by other process, random and dangerous.
In numlist there are 8 element that means for loop must execute code 8 times.
Your code must be:
for(int i = 0; i < 8; ++i)
{
sum += numList[i];
}
This code iterate until i=7, when i=8 it will end the loop.
Information on for loop
I was working on the following 2d-array program to output this result shown in picture:
I can't seem to get the min value for the result and get it displayed in array form.
The code is below:
#include<stdio.h>
#define NUMROWS 2
#define NUMCOLS 3
//accessing elements of 2D array using pointers
int main(void){
const int table[NUMROWS][NUMCOLS]={{1,2,3},{5,6,7}};
int minvals[NUMROWS];
int i, j;
int *ptr = &table;
//accessing the elements of 2D array using ptr
printf("table values: min value\n");
for(int i=0;i<NUMROWS;i++){
for(int j=0;j<NUMCOLS;j++)
printf("%d ",*((ptr+i*NUMCOLS)+j));
printf("\n");
}
for(int i=0;i<NUMROWS;i++){
for(int j=0;j<NUMCOLS;j++)
printf("%d ",*((ptr+i*NUMCOLS)+j)<minvals[i]);
}
return 0;
}
The existence of minvals would imply that you are expected to calculate the minimum value of each 'row' of table before then moving on to printing. As it stands, had your program properly calculated the minimum values of each array, your printing would be rather out of order.
There's no need to do any tricky, manual pointer manipulation. Simple array subscription is much clearer.
Let's start simple and return to basics by looking at the way we find the minimum value in a one dimensional array, as it is the core of this problem.
To find the minimum value in an array we need a few things to start:
An array
The length of the array
An initial value to compare against
The array itself is obviously each subarray of table, and the length in this case is known to be NUMCOLS. Our initial value should either be INT_MAX (or another type-appropriate maximum constant found <limits.h>), such that every element in the array is equal to or less than our initial value, or a value from the array itself.
Often times we opt for the second option here, choosing the first element in the array as our initial value, and comparing it to the second and onward elements.
As such, finding the minimum value in a single 'row' would look like this
const int row[NUMCOLS] = { 9, 2, 5 };
int min = row[0];
for (int i = 1; i < NUMCOLS; i++)
if (row[i] < min)
min = row[i];
but since we want to find and record the minimum value of each 'row' in table, we're going to use a nested loop. Instead of the min variable from before, we store each value in the associated index of our minvals array.
for (i = 0; i < NUMROWS; i++) {
minvals[i] = table[i][0];
for (j = 1; j < NUMCOLS; j++)
if (table[i][j] < minvals[i])
minvals[i] = table[i][j];
}
When it comes time to print, we're going to repeat our nested loop. Our inner loop prints each element of each 'row' of table, and we end each iteration of the outer loop by printing the value found in minvals with the same index of our 'row'.
for (i = 0; i < NUMROWS; i++) {
for (j = 0; j < NUMCOLS; j++)
printf("%6d", table[i][j]);
printf(":%6d\n", minvals[i]);
}
Here's a working example.
#include <stdio.h>
#define NUMROWS 2
#define NUMCOLS 3
int main(void) {
const int table[NUMROWS][NUMCOLS] = {
{ 9, 2, 5 },
{ 3, -4, -12 }
};
int minvals[NUMROWS];
int i, j;
for (i = 0; i < NUMROWS; i++) {
minvals[i] = table[i][0];
for (j = 1; j < NUMCOLS; j++)
if (table[i][j] < minvals[i])
minvals[i] = table[i][j];
}
puts("Table value: minimum values");
for (i = 0; i < NUMROWS; i++) {
for (j = 0; j < NUMCOLS; j++)
printf("%6d", table[i][j]);
printf(":%6d\n", minvals[i]);
}
}
A good further exercise for you would be to compose the logic of the inner loop for finding minimum values into a more generic function. Its function signature would look like
int min(int *array, size_t length);
allowing it to work on arrays of varying sizes. Then our outer loop could be as simple as:
for (i = 0; i < NUMROWS; i++)
minvals[i] = min(table[i], NUMCOLS);
The line
int *ptr = &table;
is wrong, because &table is of type int (*)[2][3] (i.e. a pointer to the entire table), whereas ptr is a pointer to a single element. Also, your pointer is non-const, so it cannot point be made to point into a const array.
If you want ptr to point to a single int value, then you should declare it the following way:
const int *ptr = &table[0][0];
Also, you are reading the contents of the array minvals, although that array contains uninitialized data. This does not make sense and causes undefined behavior.
Instead of doing complex pointer arithmetic with the expression
*((ptr+i*NUMCOLS)+j))
you can simply write the following:
table[i][j]
That way, you do not need the pointer ptr and your code is simpler.
I am trying to copy a 2d array in to another variable by reference to avoid unnecessary computation. I essentially have two 2d arrays, current_array and new_array, and I generate new_array from current_array then replace.
I am trying to program conways game of life using openmp, but I am having problems copying the new array to the old one. I have tried using *current_array=*new_array, ¤t_array=&new_array, ... and all other combinations.
I don't know much about C or pointers but the teacher insists we use C.
void NextArray(int const height, int const width, int const CurrentArray[height][width], int NewArray[height][width]){
for(int i = 0; i < height; ++i){
for(int j = 0; j < width; ++j){
NewArray[i][j] = Newpoint(i,j, CurrentArray);
}
}
}
int main(){
int CurrentArray[height][width];
int NewArray[height][width];
InitialArray=fopen("matrix.txt", "r");
for(long long i = 0; i < height; ++i){
for(long long j = 0; j < width; ++j){
fscanf(InitialArray, "%d", &CurrentArray[i][j]);
}
}
NextArray(height, width, CurrentArray, NewArray);
CurrentArray = NewArray;
return 0;
}
I expect CurrentArray to have the same information that results from the NextArray function, if you define NewPoint like this:
void NextArray(int const i, int const j, int const CurrentArray[height][width]){
if (CurrentArray[i][j]){
return 0;
}
return 1;
}
height = 2, width = 2, and "matrix.txt" as a file with the following:
0 0
1 1
then CurrentArray should be
1 1
0 0
To copy an array to an array of identical type (identical dimensions and element type), use:
memcpy(NewArray, CurrentArray, sizeof NewArray);
To make a pointer that refers to another array, use:
int (*NewArray)[width] = CurrentArray;
This works because, when CurrentArray is used in most expressions, it is automatically converted to a pointer to its first element. Since it is an array of arrays, its first element is an array. That array has type int [width], and a pointer to such an array has type int (*)[width]. So declaring NewArray to with int (*NewArray)[width] defines it to have the right type to be assigned (and act like) a pointer to the first element of CurrentArray.
Given your task, you probably want two separate arrays—you want to have both the old data and the new data available. Your title asks for a “referenced copy”, but you probably do not want a reference to the old array, because then you have only one set of data that is accessed through two different identifiers.
So I have a 2D array that I want to use later. Right now I just want to fill the empty spots.
So far I've just been messing around with array types and different default values. From my understanding a new array is filled with '0', I have tried NULL aswell.
int r = 5;
int c = 5;
int i;
int j;
int k = 0;
int area = r*c;
const char *array[r][c]; //tried char array[r][c] and other types
Setup my initial values and array here.
while(k< area){
for (j = 0; j < c; j++){
for (i = 0; i<r; i++){
if (array[i][j] == 0){
board[i][j] = ".";
}
printf("%c",aray[i][j]);
if (i = r - 1){
printf("\n");
}
k++;
}
}
}
This is where I try replacing all non filled values (all of them at this point) with ".", so the output should be a row of 5x5 dots. Instead I get weird letters and numbers. I have tried %s insead of %c, and no luck there but the output was different. Where I do %s I get some dots, but still not on a grid and the weird values show up.
Also Im pretty sure printf in a for loop, by default does it on a new line so I won't get the grid, so is there a better way of doing this?
What you have is an array of pointers. This would be suitable for a 2D array of strings, but not for a 2D array of characters. This isn't clear from your question, so I'll assume that you actually want a 2D array of characters. The syntax is: char array [r][c];.
Notably, since you used r and c which are run-time variables, this array is a variable-length array (VLA). Such an array cannot be placed at file scope ("global"). Place the array inside a function like main().
In order to use VLA you must also have a standard C compiler. C++ compilers and dinosaur compilers won't work.
Since you will have to declare the VLA inside a function, it gets "automatic storage duration". Meaning it is not initialized to zero automatically. You have to do this yourself, if needed: memset(array, 0, sizeof array);. But you probably want to initialize it to some specific character instead of 0.
Example:
#include <stdio.h>
#include <string.h>
int main (void)
{
int r = 5;
int c = 5;
char array [r][c];
memset(array, '#', sizeof array);
for(size_t i=0; i<r; i++)
{
for(size_t j=0; j<c; j++)
{
printf("%c", array[i][j]);
}
printf("\n");
}
}
Output:
#####
#####
#####
#####
#####
From my understanding a new array is filled with '0'
const char *array[r][c];
No*, you have fill it yourself in a double for loop, like this:
for(int i = 0; i < r; ++i)
for(int j = 0; j < c; ++j)
array[i][j] = 0
since your structure is a variable sized array.
Instead I get weird letters and numbers
This happens because your code invokes Undefined Behavior (UB).
In particular, your array is uninitialized, you then try to assign cells to the dot character, if their value is already 0.
Since the array is not initialized, its cells' values are junk, so none satisfied the condition of been equal to 0, thus none was assigned with the dot character.
You then print the array, which still contains garbage values (since it was never really initialized by you), and the output is garbage values.
* As stated by #hyde, this is true for local non-static arrays (which is most probably your case). Statics and globals are default initialized (to zero if that was the case here).
You have several problems:
You are declaring a pointer to the array you want, not the array
Whenever R and C are not compile time known, you can't use a built in array. You might can however use VLAs (C99 as only C standard has VLAs mandatory, C11 made them optional again), which seems like a built in array with a size not known at compile time, but has very important implications, see : https://stackoverflow.com/a/54163435/3537677
Your array is only zero filled, when declared as a static variable.
You seem to have mistake the assign = operator with the equal == operator
So by guessing what you want:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define R 5
#define C 5
int r = R;
int c = C;
int i;
int j;
int k = 0;
int area = R*C;
const char array[R][C];
int main() {
while(k< area){
for (j = 0; j < c; j++){
for (i = 0; i<r; i++){
if (array[i][j] == 0){
}
printf("%c",array[i][j]);
if (i == r - 1){
printf("\n");
}
k++;
}
}
}
//or
char** dynamic_array = malloc(r * c);
if (dynamic_array == NULL) {
perror("Malloc of dynamic array failed");
return EXIT_FAILURE;
}
memset(dynamic_array, '0', r*c);
k = 0;
while(k< area){
for (j = 0; j < c; j++){
for (i = 0; i<r; i++){
if (dynamic_array[i][j] == 0){
}
printf("%c",dynamic_array[i][j]);
if (i == r - 1){
printf("\n");
}
k++;
}
}
}
return 0;
}
I wrote a brief piece of code. It has two functions: bubbleSort is a bubble sorting function (smallest to largest), and "int main" is used to test this piece of code with an int array of size 5.
I'd like this to destructively sort the array, and not simply pass through a copy. I have looked and looked, but I am still not entirely clear how this should work. What am I missing here?
#include <stdio.h>
void bubbleSort(int values[], int n);
int main(void) {
//set simple test array to make sure bubbleSort works
int arr[5] = {5,4,3,2,1};
//run it through function, and then print the now sorted array to make sure
bubbleSort(arr, 5);
printf("%i", arr);
return 0;
}
void bubbleSort(int values[], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0, hold = 0; j < n-i; j++) {
if (values[j] > values[j+1]) {
hold = values[j+1];
values[j+1] = values[j];
values[j] = hold;
}
}
}
return;
}
Note: The rest of my code looks sound to my amateur coding mind, but please give me pointers on what i can improve, what can be better, etc. I thought about using recursion for the bubble sort but i'm not yet as comfortable with C as I'd like to be to implement that. However if you have suggestions i'll be more than happy to read them.
thanks!
Looks like your function is sorting the array (although with some bugs) and you are just printing the result incorrectly. printf doesn't know how to print arrays. Instead, you need to use a loop to print each integer one at a time:
for(int i=0; i<5; i++){
printf("%d ", arr[i]);
}
printf("\n");
After changing this, the output is 1 2 3 4 5, as expected.
However, as mentioned in the comments, there are some bugs in the implementation of the bubblesort. For example, it tries to read elements from indedex after the end of the array, which is undefined behavior (namely, j+1 can be 5, which is out of bounds). I would recommend checking your book again to get a correct implementation of bubblesort.
There is one issue in you bubble sort code which must be fixed. Your inner loop has the issue:
/* for (int j = 0, hold = 0; j < n-i; j++) { */ // ISSUE here
for (int j = 0, hold = 0; j < n-i-1; j++) { // j < n-i-1 should be the condition
This is becasue, take the case of when i = 0, i.e. the first iterartion of outer for loop. This time, j < n - i will be true when j is one less than n - which is the last index of your array. Then you do comaprision between values[j] and values[j+1], where values[j+1] is clearly out of bound of your array. This will invoke undefined behavior, and your function will not give deterministic results.
Next improvement could be that your outer loop only needs to iterate from i = 0 till i < n-1, i.e. one times less than the total elements. You are interating one time more than needed.
Third, you can use a flag to keep track of weather you swap at least once in your inner loop. If there there are no swaps in inner loop then it means that array is already sorted. So at the end of each iteration of inner loop you can see if any swap was done, and if no swaps were done then break out of the outer loop. This will improve performance in cases where array is already almost sorted.
void bubbleSort(int values[], int n)
{
int swap; // To use as a flag
// for (int i = 0; i < n; i++) {
for (int i = 0; i < n-1; i++) {
swap = 0; // set swap flag to zero
// for (int j = 0, hold = 0; j < n-i; j++) {
for (int j = 0, hold = 0; j < n-i-1; j++) {
if (values[j] > values[j+1]) {
hold = values[j+1];
values[j+1] = values[j];
values[j] = hold;
swap = 1; // swap was done
}
}
if (swap == 0) // If no swap was done
break; // Means array already sorted
}
return;
}
And, although not related to your sorting function, as others have pointed out, printf("%i", arr); is wrong, and will invoke undefined behavior because you are using a wrong format specifier in printf. It seems like you are trying to print the array. For that you can do:
// printf("%i", arr);
for (int i = 0; i < 5; i++)
printf("%d ", arr[i];)
printf("\n");
Your code already sorts the array in-place - although there is a bug in it. I'll address the subject of the question only (in-place sorting of an array in C) as comments have already highlighted the bugs with the sort function.
The print-out of the result is incorrect though as it tries to print the arr pointer as an integer:
sort.c:10:18: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("%i", arr);
~~ ^~~
1 warning generated.
However changing this to:
for (int i = 0; i < 5; i++)
printf("%i", arr[i]);
fixes the problem with the output.
Perhaps your confusion comes from how arrays are actually a syntactic way to access pointers in C. arr is a pointer. arr[1] is the same as *(arr + 1) (the contents of the pointer arr + 1 using pointer arithmetic, which increments the pointer by the sizeof the type). So when you pass arr into the function, you are passing a pointer to the existing array, then you are modifying its contents, sorting the array in-place.