i've try to compile this simple program, it will alloc a dyamic array and return it with a multiple of 5 in every location. but it doesn't work, it report me an error in the pointer.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
int n;
int i;
int* ptra;
scanf("%d", &n);
ptra = malloc(n*(sizeof(int)));
for(i=0; i<=n; i++){
ptra[i] = (5*(i+1));
printf("%d\n", ptra[i]);
}
return 0;
}
Index range for ptra must be from 0 to n-1 (both inclusive). But here:
for(i=0;i<=n;i++){
you are going out of bounds, which is undefined behaviour. Change it to:
for(i = 0; i < n; i++) {
Note: Always check the return of all the standard functions for failures (scanf() and malloc() in your code).
Your for loop is going one step beyond the limit: must go as long as i<n and not i<=n
try doing:
for(i=0; i<n; i++){
Related
I was attempting to create an array from user input in C. My code was as follows
#include <stdio.h>
#include <stdlib.h>
char** create_array(int num);
int main(){
char** my_array;
int i;
printf("%s", "Input the size of the array: ");
scanf("%d", &i);
my_array = create_array(i);
for (int m = 0; m < i; m++){
printf("%s\n", (char*)my_array[m]);
}
}
char ** create_array(int num){
char** array = malloc(num * sizeof(char*));
for (int i = 0; i < num; i++) {
char temp[32];
printf("Input element %d of the array: ", i);
scanf("%s", temp);
array[i] = temp;
}
for (int m = 0; m < num; m++){
printf("%s\n", array[m]);
}
printf("end of func\n");
return array;
}
I was having (possibly unrelated?) issues with segmentation faults until I replaced the declaration of temp from char *temp; to char temp[32];. I am not sure of why declaring temp as a char pointer creates the segmentation fault, if that is a simple related answer let me know, if not I will ask in another question.
However, when I run this code, upon inputting
Input the size of the array: 2
Input element 0 of the array: value0
Input element 1 of the array: value1
I get
value1
value1
end of func
Segmentation fault (core dumped)
So to me it seems like temp somehow isn't changing when the for loop executes next iteration. I'm not sure why or how that would ever happen though. I also tried changing
printf("%s\n", my_array[m]);
to
printf("%s\n", (char*)my_array[m]);
but that didn't seem to help either.
Any ideas?
Thanks
I believe this is what you're looking for. The trick is allocate the memory for the strings on the heap. Saving pointers to char temp[32]; is dangerous because it's in automatic storage. As #Spikatrix said in a comment, that memory is not guaranteed to be in a valid state between each iteration of the loop. With the data on the heap, there's a well-defined region of memory set aside and identified by the pointer returned from malloc.
There's also a lot of good reason to not use scanf. As is, your code does not do any bounds checks and can easily overwrite the 32-byte array allocated for each string.
#include <stdio.h>
#include <stdlib.h>
char** create_array(int num);
int main(){
int num_strings;
printf("Input the size of the array: ");
scanf("%d", &num_strings);
printf("\n");
char** my_array = create_array(num_strings);
for (int i = 0; i < num_strings; i++){
printf("%s\n", my_array[i]);
}
for (int i = 0; i < num_strings; i++) {
free(my_array[i]);
}
free(my_array);
}
char** create_array(int num) {
char** array = malloc(num * sizeof(char*));
for (int i = 0; i < num; i++) {
array[i] = malloc(32);
printf("Input element %d of the array: ", i);
scanf("%s", array[i]);
printf("\n");
}
printf("end of func\n");
return array;
}
I'm trying to count the number of elements in an array as a pointer as the code followed:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *) malloc(sizeof(int*));
for(int i=0; i<8; i++)
{
printf("The number: " );
scanf("%d", &ptr[i]);
}
int size = sizeof(ptr)/sizeof(int);
printf("%d\n", size);
return 0;
}
I have tried the syntax for an array size = sizeof(ptr)/sizeof(int);but I got the wrong answer which is 1 for all cases. I don't know how to get the correct answer, which is 8 for this case
Unfortunately, you cannot get the size of an array allocated with malloc (because you are actually getting the size of a pointer). You must always store that somwhere else. Since you always allocate 8 elements, why not make it a static array?
#include <stdio.h>
int main()
{
int arr[8];
for(int i=0; i<8; i++)
{
printf("The number: " );
scanf("%d", &arr[i]);
}
int size = sizeof(arr)/sizeof(int);
printf("%d\n", size);
return 0;
}
How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.
'scanf' won't pass on my the value n into the for loop
appreciate your time to help thanks. terminal prints the size of array. I hope to scan for that value and call it 'n' . This value 'n' is then suppose to be passed down to the loop where random numbers less then 999 are assigned to different parts of the array.
#include <stdio.h>
#include <stdlib.h>
int n;
int arraySize;
int randN;
int rand();
int parameter = 999;
int main()
{
printf("What is the size of the array\n");
scanf("%d\n", &n);
//here is the scanf
int i;
for(i = 0 ; i < n; i++ )
{
int array[n];
randN=rand();
if (randN <= parameter)
{
array[i]=randN;
return 0;
}
return 0;
}
}
The array is declared as the first line in the body of the loop.
This means, for every loop iteration, the array is created, one element is set, and then the array ceases to exist.
If you want the loop to populate the whole array, declare the array BEFORE the loop. That will also ensure the array can be used AFTER the loop .... with all its elements as populated in your loop.
Drop the \n at the end of format string. scanf tries to get input as specified in the format string, the \n forces the user to enter additional newline
scanf("%d", &n);
See answer of user3279954
See comment of AnT
the "return 0;" statements will terminate your program in the first iteration of the loop, regardless of the value returned in the call to rand()
Also: Don't declare library functions (like rand()) yourself, instead, include the appropriate header file, here stdlib.h which was included already.
#include <stdio.h>
#include <stdlib.h>
int n;
int arraySize;
int randN;
int parameter = 999;
int main()
{
printf("What is the size of the array\n");
scanf("%d", &n);
int array[n];
int i;
for (i = 0 ; i < n; i++ )
{
// This loop below should be optimized for any productive use
// easy solutions like random%1000 (yielding values from 0
// to 999) will bias some values over others.
do {
randN=rand();
} while (randN > parameter);
// This loop above should be optimized for any productive use
array[i]=randN;
}
for (i = 0 ; i < n; i++ )
{
printf("%i ", array[i]);
}
return 0;
}
Ok, so there are some things with your code:
#include <stdio.h>
#include <stdlib.h>
int n;
int arraySize;
int randN;
int rand();
int parameter = 999;
int main()
{
printf("What is the size of the array\n");
scanf("%d", &n); // remove the \n
// in C, you have to use a const to create an array
const int arrSize = n;
// create the array BEFORE, entering the for loop
int array[arrSize];
int i;
for(i = 0 ; i < n; i++ )
{
// this guarantees that you will get a number less than "parameter"
randN=rand() % parameter;
array[i]=randN;
// return 0; you don't want this return
}
// so you can see what got stored
for(i = 0 ; i < n; i++ )
printf("%d ", array[i]);
return 0;
}
EDIT: added a printf for the values in the array
I am working with 2D arrays for the first time for a sudoku checker program; below is my code.
My program compiles without error, but when I run it, it gives me a segmentation fault.
It has been a while since I last coded, so I am unsure what I'm missing. I've also never had to deal with this error before.
My Code:
#include <stdio.h>
#include <stdlib.h>
int sudokuCheck();
int arrayMake();
#define SIZE 9
int main(){
int sudokAmount;
printf("Please Enter the amount of solutions to solve:\n");
scanf("%d",&sudokAmount);
arrayMake();
//sudokuCheck(sudokAmount);
return 0;
}
int arrayMake(){
int j;
int i;
int** sudoArr;
sudoArr = malloc(sizeof(int*) * SIZE * SIZE);
printf("Please Enter Sudoku Solutions(By rows)\n");
for(i = 0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
scanf("%d\n", &sudoArr[i][j]);
}
}
for(i = 0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
printf("%d \n", sudoArr[i][j]);
}
}
return 0;
}
First of all, you allocate memory for the matrix wrong way. Correct will be:
int** sudoArr = (int**)malloc(SIZE * sizeof(int*));
for (int index=0; index < SIZE; ++index)
{
sudoArr[index] = (int*)malloc(SIZE * sizeof(int));
}
Link to online compiler with correct version of your code: correct sources