getting unexpected values in my simple program in C - c

when I am compiling this small program I am getting different values as output, instead of getting numbers from 0 to 5. And the size of array is always 8. The different values I am getting are:
-981774704
32767
0
0
4195728
0
Any tips would be really valuable. Thank you
#include <stdio.h>
int main() {
int array[10];
int i;
for (i = 0; i < 6; i++) {
printf("%d\n", array[i]);
}
int z = sizeof(&array);
printf("\n Size of array is %d", z);
return 0;
}

You aren't assigning any values to the array, so you're getting the uninitialized values.
You need to do something like array[0] = 5; //or some value etc.
If you want an array of size 8, with the numbers indexing the array stored in it, so {0, 1, 2, 3, 4, 5, 6, 7}, you could do something like:
int array[8];
for(int i = 0; i < 8; ++i)
{
array[i] = i;
}

the elements of the array are uninitialized therefore it's printing garbage value...first initialize the elements with values...you can do this...
#include<stdio.h>
int main()
{
int array[10] ;
int i;
for (i = 0; i < 6; i++)
{
array[i]=i;
printf("%d\n", array[i]);
}
int z = sizeof(&array);
printf("\n Size of array is %d", z);
return 0;
}
if you want the array to be initialized automatically then declare the array globally...
if you want to get the size of the whole array remove &
sizeof(array);

C will not initialize your array to any default value. When you create the array it will be full of garbage values (nothing relevant or defined). Always initialize your data using memset or something equivalnet.
So if you are expecting a value of 0 on a new array then initialize it like this:
memset(array, 0, sizeof(array));

you have to initialize your array first, memory may not be filled with 0 by default

Related

Error expected identifier or '(' int &arrayreturn[I] = {I}

#include "stdio.h"
int printsomething(int *array, int arrayreturn[5]) {
int i;
for(i = 0; i < 10; ++i) {
printf("%d\n", array[i]);
}
for(i = 0; i < 5; ++i) {
int &arrayreturn[i] = {i};
}
return 0;
}
int main() {
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// int *arraypointer = &array;
int arrayp[5];
int i;
printsomething(array, arrayp);
for(i = 0; i < 5; ++i) {
printf("%d\n", arrayp[i]);
}
return 0;
}
I am learning C and right now just playing with arrays and pointers trying to get comfortable. This bit of code has the goal of passing an array to a function, which was successful before I added the second part. That second part being assigning values in the called function to an already initialized array. Since we can't directly return an array I understood this was the way to do it. What exactly do you all think is going wrong here? And I just completely off the target?
If you want to assign values to the array elements you need to use [] to access the elements and = to assign them. I cannot really explain your code because it is unclear how you came to the conclusion that you need to write int &arrayreturn[i] = {i};. Your loop can be this:
for(i = 0; i < 5; ++i) {
arrayreturn[i] = i;
}
the first problem is that when you have a parameter of the form int arrayreturn[5] you actually just pass an int pointer not an entire array of 5 elements. int arrayreturn[5] and int *arrayreturn compile to exactly the same cpu instructions. I never use the int arrayreturn[5] syntax because i think it is confusing so i rather just pass a pointer and this is common practice as far as i know.
secondly in the second part of your code you try to declare a new array of size i by calling int &arrayreturn[i] = {i} this is not possible because of multiple reasons mostly because you cant dynamically allocate arrays on the stack. it should be arrayreturn[i] = i

why do i not get the correct value for sum?

#include <stdio.h>
#include <stdlib.h>
int sumArray(int* p);
int main(){
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, sum;
int* p = array;
sum = printf("The sum of the array is: %d", sumArray(p));
return 0;
}
int sumArray(int* p){
int sum = 0;
while(*p){
sum += *p;
p++;
}
return sum;
}
when i run this code i get a 6-digit value for sum, which looks more like an address. so what exactly am i doing wrong here?
while(*p) is a pretty idiomatic way of processing character strings in C because they have the useful property of being null-terminated. Once the null terminator (character with numeric value of 0) is reached, *p is 0 and the loop ends.
Your array does not have this property so while(*p) is true for the entire length of your array, then it goes out of bounds, which is undefined behavior.
Your options are:
Pass the size along with the array, and use int i = 0; while (i < LENGTH){} or more idiomatically for(int i = 0; i < LENGTH; i++)
Use a designated sentinel value to indicate the end of the array and use while (*p != SENTINEL)
Former option is the least hassle and doesn't require you to designate an arbitrary int as a magic number.

C stack smashing detected in array

I am trying to solve a question.
If in array a number is duplicated I make him 0. My code is throwing an error could you please help me ?
#include <stdio.h>
int main() {
int a[] = {-3, -2, -1, -7, -3, 2, 3, 4, 2, 7, 10, 3};
int length = 12;
int zero_duplicates(int laenge, int *a) {
int zero[] = {};
int k = 0;
int j = 1;
for(int x=0; x<laenge; x++)
{
if (zero[*a] == 1) {
*a = 0;
} else {
zero[*a] = 1;
k++;
}
a++;
}
return k;
}
int count = zero_duplicates(length, a);
printf("%d -- ", count);
for(int i = 0; i < length; i++) printf(" %i ", a[i]);
return 0;
}
This ...
int zero[] = {};
... is not a valid array declaration in C. If your compiler accepts it as an extension then it ought at least to be emitting a warning, and even then it probably doesn't mean what you think it means. Specifically, among the most likely extensions would be to interpret that as declaring a zero-length array (which also would constitute an extension), such that accessing any element overruns the array bounds.
Moreover, no matter how long the array is, if any of the elements of the input array are negative (as is the case in the example) then zero[*a] will constitute an out-of-bounds access when a points to one of those elements.
Overall, you need a different approach. What you're trying to do is not viable.
As a separate matter, C does not support nested functions, so your code is relying on yet another extension in that respect. This particular issue can be resolved by lifting the nested function out of main(), however, putting it above instead of inside.

To check if array value is NULL i.e. has been set or not

The array takes the garbage value if it is not initialized. To check whether the array is NULL we will use NULL or 0 to initialize the array while declaring.
If the user inserts the value 0 for an array say a[1]=0 and he didn't give the value for a[3] but both a[1] = 0 a[3] = 0.
Without initializing the array as NULL
#include <stdio.h>
main(){
int i, a[5];
a[0] = 0;
a[1] = 2;
a[3] = 4;
a[4] = 5;
for (i = 0 ; i < 5 ; i++){
printf("%d ", a[i]);
}
}
here a[2] has some garbage value.
Initializing the array to NULL or 0
#include <stdio.h>
main() {
int i, a[5] = {0};
a[0] = 0;
a[1] = 2;
a[3] = 4;
a[4] = 5;
for (i = 0 ; i <5 ; i++) {
printf("%d ", a[i]);
}
}
Here a[2] is not inserted but it takes the value 0
If the user's input is 0 (here a[0] = 0) then how can he actually know whether the value is inserted or not
Problematic first is that you seem to have a misunderstanding about NULLand 0. In C NULL is usually the number 0, but made to something that fits to any type. So, although you shouldn't rely on it nor use it at all, int i = NULL is the same as int i = 0. And this leads to the general problem:
Convention of a "NULL"/"OPTIONAL"/"NIL"/"NOT_SET" value
For pointers this can easily be done by setting them to NULL, since a valid pointer will have any value, but NULL. Doing this for normal types, like int, is not natively possible, because if int can be all integers / Z where do you want to put your "exceptional" value?! That's the reason why often pointers, instead of the direct types, are used, or some more fancy stuff like boost optional in C++.
So you would have to write something like:
#include <stdlib.h>
#include <stdio.h>
#define ARRAY_SIZE 5
int main (void)
{
int number = 42;
int *array[ARRAY_SIZE] = {0};
array [2] = &number;
int i;
for (i = 0; i < ARRAY_SIZE; i++){
if (array[i] != NULL){
printf("Position %d was set to %d\n",i,*array[i]);
}
}
return 0;
}
However be cautious when using the address of auto ("stack") variables, usally you will have to use dynamic variables, i.e. use malloc and free.

Getting garbage value while passing an entire array to a function

I'm trying to pass an entire array to the function but the last value i get is always a garbage value and not 3. Please point out where I've made a mistake.
#include<stdio.h>
#include<conio.h>
main() {
int array[3] = {0, 1, 2, 3};
display(&array[0], 3);
}
display(int *j, int n) {
int i;
for(i=0; i<=n; i++) {
printf("\n%d", *j);
j++;
}
}
You have an off-by-one error in your for loop. Your array has only three elements. You try to read four elements instead of three.
Change your code to this (note the < instead of <=):
for (i = 0; i < n; i++) {
You also try to initialize the array with four elements when it only has room for three:
int array[3] = {0, 1, 2, 3};
Maybe you can try to change your compiler settings to flag this as a warning/error. Then you might get something like this that would notify you of the problem:
prog.c: In function ‘main’:
prog.c:13: error: excess elements in array initializer
prog.c:13: error: (near initialization for ‘array’)
The array variable represent an address of first element so no need to use & address operator with the function call and another issue is with size of an array.
main() {
int array[4] = {0, 1, 2, 3};
display(array, 3);
}
display(int *j, int n) {
int i;
for(i=0; i<=n; i++) {
printf("\n%d", *j);
j++;
}
}
There a few observations in the code:
1. main() should be int main(void) or int main(int argc, char **argv). Also you need to return an int value from main when to change it to int main(void) or int main(int argc, char **argv)
2. You are initializing an array of 3 elements with 4 values.
Either declare as int array[3] = {0, 1, 2}; or as int array[] = {0, 1, 2, 3}; (this will create an array with 4 elements)
3. display(int *j, int n) should have a return type say void display(int *j, int n) (otherwise it default to int in which case the function is not returning any value). In this case you will have to define the function before using.
4. In current case, to the function display you are passing an array of 3 elements and accessing element at index 3 (when i equals n) in the for loop which is the 4th element (i.e. out of bounds which is undefined behavior). Remember that array in C is zero indexed. So for(i=0; i<=n; i++) should be for(i=0; i<n; i++)
Hope this helps!
You cannot pass "an entire array to a function" -- C does not do this. Instead, you are passing a pointer to the first element of the array.
main() {
int array[3] = {0, 1, 2, 3};
main should be declared int main(int argc, char* argv[]). It's not that horrible to type, and you can even get your text editor to do it for you, if you care enough.
You have declared array to contain only three items, but store four items into the array. This should have thrown a compile warning at the least. Pay attention to those warnings. Don't specify the size of your array unless that size is vital (Say, if you wanted to keep track of US states, then int states[50] = { ... }; might make sense. For now. Maybe this is a bad example.)
for(i=0; i<=n; i++) {
printf("\n%d", *j);
j++;
for(i=0; i<=n; i++) is very often a bug -- C array indexes run from 0 to n-1, not 0 to n. You're reading one-past-the-array, and that value is not surprisingly garbage.
Further this code is awkward; you should just use printf("\n%d", j[i]) and not increment j each time. Incrementing two variables as "loop variables" this way is a recipe for writing bugs in the future. (If you need to update two variables with every loop iteration, place both in the last section of the for(;;i++, j++) loop.)
Your array is declared to have 3 elements yet you initialize it with 4:
int array[3] = {0, 1, 2, 3};
You create an array for only 3 integers, but put 4 in it. But the error is when you print the array, you print four entries, though only three exist.

Resources