Why does my C dynamic array give me access violation? - c

Here is the code I have.
int *arr; // Indented this line
int sizeOfArr = 0;
printf("Enter size of arr.\n");
scanf("%d", &sizeOfArr);
arr = malloc(sizeOfArr * sizeof(int));
for (int i = 0; i < sizeOfArr; i++) {
scanf("%d", arr[i]);
}
For example, if the size of the dynamic array is 5, and I proceed to enter the input "1 2 3 4 5", the entire program crashes and gives me access violation.

In order to store array elements you need to use scanf("%d", &arr[i]); instead of
scanf("%d", arr[i]);
& in C is used to refer to address of a variable. So,by using &arr[i] you are telling your program to store the input variable at ith index of array arr[].
So the correct code will be
int *arr;
int sizeOfArr = 0;
printf("Enter size of arr.\n");
scanf("%d", &sizeOfArr);
arr = malloc(sizeOfArr * sizeof(int));
for (int i = 0; i < sizeOfArr; i++) {
scanf("%d", &arr[i]); //notice the diff here
}

Related

Issue with using array pointers (C)

I am writing a program that is meant to read in two arrays and find the difference between the two (elements found in set A but not in set B).
The sets are stored using arrays of 1s and 0s (1s for elements that exist and 0s for elements that don't). I have the following code written and can't seem to understand why I am getting these warnings
warning: comparison between pointer and integer [enabled by default]
if(p==1 && q==0)
^
warning: assignment makes pointer from integer without a cast [enabled by default]
set_difference = 1;
I have the following code written. It will not return a value, either.
#define N 10
void find_set_difference(int *set_a, int *set_b, int n, int *set_difference);
int main(void)
{
int i, k;
int n;
printf("Enter the number of elements in set A: \n");
scanf("%d", &n);
int a[n];
printf("Enter the elements in set A: \n");
for(i=0; i<n; i++){
scanf("%d", &a[k]);
a[k] = 1;
}
printf("Enter the number of elements in set B: \n");
scanf("%d", &n);
int b[n];
printf("Enter the elements in set B: \n");
for(i=0; i<n; i++){
scanf("%d", &b[k]);
b[k] = 1;
}
int set_dif[N];
find_set_difference(a, b, N, set_dif);
printf("The difference of set A and set B is: \n");
for(i=0;i<10;i++){
if(set_dif[i]==1)
printf("%d ",i);
}
return 0;
}
void find_set_difference(int *set_a, int *set_b, int n, int *set_difference){
int *p, *q;
for(p=set_a; p<set_a+n; p++){
for(q=set_b; q<set_b+n; q++){
if(p==1 && q==0)
set_difference = 1;
else
set_difference = 0;
}
}
}
Any assistance with formatting and using pointers would be helpful, as I am still new to coding and am having difficulty understanding the concepts.
The following checks the value of the pointers:
if(p==1 && q==0)
You want to check the pointed values.
if(*p==1 && *q==0)
The following sets the value of the pointer:
set_difference = 1;
You want to set the pointed variable.
*set_difference = 1;
This answer only addresses the warnings you asked about. There are a number of other major problems, but I don't want to do your homework for you. Think about how many different variables do you want to set.
You are currently setting one.
You are currently setting it n*n times.
you some problems in your code:
the value of variable k isn't being initialized in the loop as it's used being as an iterator, also a[k] = 1 doesn't make any since as this is an array not hash table, assume if input1 = 1, 2, 3, 4, 5 and input2 = 6, 7, 8, 9, 10, the way you write that line makes that input1 is same as input2 :
for(i=0; i<n; i++){
scanf("%d", &a[k]);
a[k] = 1;
}
so you should do :
for(i=0, k = 0; i<n; i++, k++){
scanf("%d", &a[k]);
}
using the same variable n for 2 different arrays can result in some errors if the user entered different sizes for the 2 different arrays
so use another variable to get the size of the second array instead of n that's being used for the first array
the size of the set_dif in line :
int set_dif[N];
is better to be the size of the smallest array of them, but it wouldn't make any difference if its size is greater than that.
in this line :
if(p==1 && q==0)
you are comparing address which is pointer p with a value which is 1
so instead you should compare the value in that address with value 1, so you should do: if(*p==1 && *q==0)
in this line:
set_difference = 1;
set_difference is a pointer to the array which means it's an address, so you can't do address = Value, instead you should do the:
set_difference[i] = 1;
where i is an iterator
also in the line:
if(*p==1 && *q==0)
you should compare if(*p!=*q) as not to make the problem discussed in point 1
and the array called set_dif should be initialized with ones.
instead of:
printf("%d ",i);
write: printf("%d ",a[i]); , as to achieve what are seeking with this line, you should look for something called hash table
with all that being said, this is the full edited code:
#include <stdio.h>
void find_set_difference(int *set_a, int *set_b, int n, int m, int *set_difference);
int main(void)
{
int i, k = 0;
int n, m;
printf("Enter the number of elements in set A: \n");
scanf(" %d", &n);
int a[n];
printf("Enter the elements in set A: \n");
for(i=0, k = 0; i<n; i++, k++){
scanf(" %d", &a[k]);
}
printf("Enter the number of elements in set B: \n");
scanf("%d", &m);
int b[m];
printf("Enter the elements in set B: \n");
for(i=0, k = 0; i<n; i++, k++){
scanf("%d", &b[k]);
}
int set_dif[n];
for (int j = 0; j < n; ++j) {
set_dif[j] = 1;
}
find_set_difference(a, b, n, m, set_dif);
printf("The difference of set A and set B is: \n");
for(i=0; i< n ;i++){
if(set_dif[i] != 0)
printf("%d \t",a[i]);
}
return 0;
}
void find_set_difference(int *set_a, int *set_b, int n, int m, int *set_difference){
int *p, *q;
int i = 0;
for(p = set_a; p < set_a + n; p++, i++){
for(q = set_b; q< set_b + m ; q++){
if(*p==*q)
set_difference[i] = 0;
}
}
}
and this is some example output:
Enter the number of elements in set A:
5
Enter the elements in set A:
1
3
4
5
6
Enter the number of elements in set B:
5
Enter the elements in set B:
2
3
4
6
8
The difference of set A and set B is:
1 5

Segmentation fault when using a 1D array

#include <stdio.h>
int main()
{
//Initialize array
int n; // n is use to decide the size of array
int x[n];
int y[n];
printf("enter the size of array:");
scanf("%d", &n);
if (n > 0)
{
for (int i = 0; i < n; i++)
{
printf("enter elements : \n");
scanf("%d", &x[i]);
}
}
printf("Array in reverse order: \n");
//Loop through the array in reverse order
for (int i = n - 1, j = 0; i >= 0; i--, j++)
{
y[j] = x[i];
printf("%d ", y[j]);
}
return 0;
}
In the above program, I have created a array whose size can be decided by the user. The user can also put elements in it.
After that I want to reverse this array and store the data in another array. But I get this error again and again. I am using CodeBlocks with the GCC compiler.
When the x and y arrays are created, n is uninitialized. There's no knowing how large these arrays will be. You loops are almost certainly accessing the array out of bounds.
You want to read n, then create the arrays. Of course you also want to error check the result of scanf.
int n; // n is use to decide the size of array
printf("enter the size of array:");
scanf("%d", &n);
int x[n];
int y[n];

how can i solve segmentation error in terminal message?

I wrote a simple program to take names and numbers from the user and store it in an array, then compare between each cell until it reach the maximum grade then it displays it. The problem is that when it run it shows a message (segmentation fault (Core dump)). I really don't know what my mistake is.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf
#include <stdlib.h>
#include <stdio.h>
#define SIZE_OF_WORD 10
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char **name=(char**)malloc((sizeof(char*)*n));
for (int i = 0; i < n; i++) {
name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
}
float *score=(float*)malloc((sizeof(float)*n));
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}

Copy all array elements into another array in C

I done with my logic which is actually used to copy a Array elements into another Array but in the final output(Point 1) of printing statement is not working well as I expecting.
#include <stdio.h>
int main()
{
int arr[50],n,key,loc;
printf("Enter size of the Elements:\n");
scanf("%d", &n);
printf("Enter %d Elements\n", n);
for(int i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}
//int a = arr[i];
printf("Enter the Element to insert:\n");
scanf("%d", &key);
printf("Enter the Location to insert:\n");
scanf("%d", &loc);
for(int i=n-1;i>=loc;i--)
{
arr[i+1] = arr[i];
}
arr[loc] = key;
printf("Result of Array:\n");
for(int i=0;i<=n;i++) //Point 1
{
printf("%d\n", arr[i]);
}
return 0;
}
Its expecting to print the copied value to print but its not showing the last element of the array.
eg:
a[] = 1,2,3
b[] = 8,9
Expecting o/p:
1,2,3,8,9
Actual o/p:
1,2,3,8
When you insert your element into your array, the size of your array increases; you should put a n++ before printing.
Are you sure that is the right code that you are trying to solve? I don't see anything wrong with that logic except the potential for buffer overflow from the input. I think your logic is correct. But instead of declaring a size for the array, you can just let the value from user input do that. I posted the code below, just a small fix to make your code to become dynamic because there isn't anything wrong with your code logic.
#include <stdio.h>
int main()
{
int n,key,loc;
printf("Enter size of the Elements:\n");
scanf("%d", &n);
int arr[n + 1];
printf("Enter %d Elements\n", n);
for(int i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}
//int a = arr[i];
printf("Enter the Element to insert:\n");
scanf("%d", &key);
printf("Enter the Location to insert:\n");
scanf("%d", &loc);
for(int i=n-1;i>=loc;i--)
{
arr[i+1] = arr[i];
}
arr[loc] = key;
printf("Result of Array:\n");
for(int i=0;i<=n;i++) //Point 1
{
printf("%d\n", arr[i]);
}
return 0;
}

How to get the sum of two index in an array in C?

Im making a code for an array that has a dynamic size and filling the array manually.Then, it will print. It will also ask for a number and finding the index that is equal to the two indexes.
I using codeblocks for this code. Id tried for loop to find the two indexes that is eqaul to the inputed number.
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i,", array[i]);
}
if (size >= 1)
printf("%i", array[size-1]);
printf("]\n");
int num;
printf("Enter number to be calculate: ");
scanf("%d",num);
for(int i= 0; i < size - 1; i++){
if (array[i] + array[size-1] == num){
printf("%d %d", array[i],array[size-1]);
}
size--;
}
}
int main(void) {
int count;
int num;
int sum;
printf("Enter the size of the array:\n");
scanf("%d", &count);
int *array = malloc(count * sizeof(*array));
if (!array) {
printf("There was a problem you entered");
exit(EXIT_FAILURE);
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < count; i++)
scanf("%d", &array[i]);
printArray(array, count);
}
I expect the output:
Index 1 and 5 are eqaul to the inputed number.
but it gives error.
To begin with, the following bug is one of the problem -
scanf("%d",num);
should be -
scanf("%d", &num);
The final loop in printArray is basically iterating through the array one element both upwards & downwards at the same time.
So, for n=6, if sum of either (a[0]+a[5]), (a[1]+a[4]) or (a[2]+a[3]) does not equal the required number , it would show up as unmatched.
This loop should be replaced by a nested loop so that inner loop iterates from j=i+1 to size-1 to allow check for a[i]+a[j] == num for all possible permutations of array indexes.

Resources