I am fairly new to learning C and dealing with pointers in the context of arrays is confusing the heck out of me. I have an original array that was provided with multiple duplicate integer values. What I am trying to do is create a new array and pass only one of each integer to the new array using pointers rather than the numbers in brackets but the output I'm getting is very wrong. I'm not sure if it's an issue with comparing the integer from the original array, or with updating the new array after comparison. P.S. this is my first post on stackoverflow so if I am formatting this incorrectly or leaving out pertinent details, I apologize
Here is my code:
#include <stdio.h>
void main(){
int original[14] = {3, 4, 5, 3, 2, 6, 3, 4, 2, 3, 2, 3, 3, 4};
int values[14];
int count[14];
int x = 0;
int i, valCheck, *ip, *vals;
int valsAdd = 0;
int n = 14;
vals = values;
for(ip = original; ip < original n;ip ){
valCheck = 0;//using this as a Boolean to determine whether the number is a duplicate or should be added to the array
for(int j = 0; j < 14;j ){
vals = &values[j];
if (*vals == *ip){
valCheck = 1;
}
}
if (valCheck ==0){
vals = &values[x];
*vals = * original;
x ;}
}
for(i=0;i<14;i ){
printf("Value %d\n", values[i]);
}
}
The idea is that the inner for loop parses the new array to make sure the number isn't in there already, and if it's not, add it to the new loop at index x then increment x, and finally print the whole loop. The output I'm expecting for would be:
Value 3
Value 4
Value 5
Value 2
Value 6
Value 0
Value 0
Value 0
Value 0
Value 0
Value 0
Value 0
Value 0
Value 0
However, this is the output I'm getting:
Value 3
Value 3
Value 3
Value 3
Value 3
Value 3
Value 3
Value 3
Value 3
Value 0
Value 0
Value 0
Value -449459208
Value 32766
Anyone know what I am doing wrong here?
CodePudding user response:
First, remember that automatic variables in C doesn't have any initial value (unless you explicitly initialize them), so your values
array can contain random values. Also, I think you need to use *vals = *ip;
instead of *vals = * original;
. This code works for me:
#include <stdio.h>
void main(){
int original[14] = {3, 4, 5, 3, 2, 6, 3, 4, 2, 3, 2, 3, 3, 4};
int values[14] = {0};
int count[14];
int x = 0;
int i, valCheck, *ip, *vals;
int valsAdd = 0;
int n = 14;
vals = values;
for(ip = original; ip < original n; ip ) {
// using this as a Boolean to determine whether the number is a duplicate or should be added to the array
valCheck = 0;
for(int j = 0; j < n; j ) {
if (values[j] == *ip){
valCheck = 1;
}
}
if (valCheck == 0) {
values[x] = *ip;
x ;
}
}
for(i = 0; i < 14; i ) {
printf("Value %d\n", values[i]);
}
}
I initialize all elements of the values
array to 0
, you can use -1
or any other value that indicates empty rooms for you. C has dynamic memory allocation with malloc
, etc. that you can use it too for increasing array size based on your need.