Array organization (C Programming) -
as beginner, have come across error in visual studio can't figure out how fix.
the following code made solve array problem. array have duplicate values inside of it, thus, program has remove them , organize remaining ones, returning new size of array.
for example: {1, 1, 2, 2, 5, 6, 8} ----> {1, 2, 5, 6, 8}.
the cup integer counts nulls in unorganized array and, used later on switch between values inside, organization.
the errors are:
**warning c4047 '=': 'int' differs in levels of indirection 'int *'** and:
**warning c4047 '=': 'int' differs in levels of indirection 'void *'** on lines: 23, 25, 35 (i have added line numbers in code below).
void main() { int a[] = { 1, 1, 1, 1, 2, 5, 6, 8, 8, 2, 5, 6, 2, 1, 8, 3 }; int sizearr, i; sizearr = fixarr(a, sizeof(a)); (i = 0; < sizearr; i++) { printf("%d ", a[i]); } } int fixarr(int *ptr, int size) { int arrs1, arrs2, cup; (arrs1 = 0; arrs1 < (size--); arrs1++) { (arrs2 = (arrs1++); arrs2 < size; arrs2++) { //23 if (*(ptr + arrs1) = (ptr + arrs2)) { cup++; //25 *(ptr + arrs2) = null; } } } (arrs1 = 0; arrs1 < cup; arrs1++) { (arrs2 = 0; arrs2 < (size--); arrs2++) { // 35 if (*(ptr + arrs2) = null) *(ptr + arrs2) = *(ptr + (arrs2++)); } } return cup; }
there several issues in code:
sizeof(a)not evaluate number of elements ina, size in bytes required objecta. ifaarray, can number of elementssizeof(a) / sizeof(a[0]), ifapointer, cannot determine number of elementsaalone.nullnot valid valueint, cannot use methodintarray.your comparisons incorrect: use assignment operator
=instead of equality operator==.you should declare function
fixarrbefore callingmain.
here simpler version uses two finger method: iterating 1 index , storing unique elements same array index:
#include <stdio.h> int fixarr(int *ptr, int size) { int i; // index reading (first finger) int j; // index writing (second finger) int k; // index searching duplicates (i = j = 0; < size; i++) { (k = 0; k < j; k++) { if (ptr[k] == ptr[i]) break; } if (k == j) { // element ptr[i] not found ptr[j] = ptr[i]; // copy new unique element j++; // increment new element count } } return j; // new size } int main(void) { int a[] = { 1, 1, 1, 1, 2, 5, 6, 8, 8, 2, 5, 6, 2, 1, 8, 3 }; int size = sizeof(a) / sizeof(a[0]); int i, newsize; printf("original array:"); (i = 0; < size; i++) { printf(" %d", a[i]); } printf("\n"); newsize = fixarr(a, size); printf("fixed array:"); (i = 0; < newsize; i++) { printf(" %d", a[i]); } printf("\n"); return 0; }
Comments
Post a Comment