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;
}
Related
im really new to programming, c is my first language
i want to create an array with a size set by scanf
it should start with startValue (second scanf) and then printf the rest of the array but with startvalue+1
so for example if i type in:
3 // --> size of the array
4 // --> my starting point/startValue
the programm should give me:
4
5
6
after several hours of watching videos/reading online and trial and error i just dont know how to solve this problem :( i really appreciate your help thank you
#include <stdio.h>
int main() {
int size;
int startValue;
scanf("%d\n %d", &size, &startValue);
int array[size];
array[0] = startValue;
for(int i = 0; i<size; i++) {
printf("%d\n", array[i]);
}
return 0;
}
As you want desired output: 4 5 6
for this you need to assign value to the rest of elements also as did with
array[0] = startValue;
I've tried to assign it the way you wanted, may be this would help you to understand
#include <stdio.h>
int main() {
int size;
int startValue;
scanf("%d\n %d", &size, &startValue);
int array[size];
for(int i = 0; i<size; i++)
{
array[i]= startValue;
printf("%d ", array[i]);
startValue=startValue+1;
}
return 0;
}
I'm assigning values to
array[0] & array[1] through this
array[i]= startValue;
and incrementing the value of startValue by +1 through this
startValue=startValue+1;
line
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 writing a program which scanf integers and printf in double.
Here is my code:
int main(void) {
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
for(int i=0;i<arraySize;i++) scanf("%lf", &vector[i]);
for(int a=0;a<arraySize;a++) printf("VECTORS:[%lf]",vector[a]);
}
Since I need to for loop every element in the array then printf all of them one by one.
this is the output I had:
VECTORS:[1.000000] VECTORS:[2.000000] VECTORS:[3.000000]
How can I change the format of the printf function and get ouput like this:
VECTOR: [ 1.000, 2.000, 3.000 ]
Your one major mistake is your array size. I know your compiler won't issue any warning but this is not any feature which language provide so size must be a
constant numerical value or const expression.
So in short you can't create array After asking size from user. This is completely wrong.
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
You must make size const. If you want less values than the declared size you can decrease the no of times for loop will run but you can't decide array size as inputted by user.
const int size = 10; // this is how your size should be. Even your compiler allowed VLA you should not try this. size of arrays must be constant.
int main()
{
unsigned int i,s;
int arr[size];
printf ("Enter the size of array.");
scanf("%d",&s);
for(i = 0 ; i<s;i++){
scanf("%d",&arr[i]);
}
for(i = 0 ; i<s;i++){
arr[i] = arr[i]*arr[i];
}
for(i = 0 ; i<s;i++){
printf("%d",arr[i]);
}
}
Print VECTOR once then loop over all the vectors and output them in the desired format.
const int size = 10;
int main(void) {
double vector[size];
for(int i=0;i<size;i++)
scanf("%lf", &vector[i]);
printf("VECTOR: [ ");
for(int a=0;a<size;a++){
printf("%lf", vector[a]);
if(i < size - 1)
printf(", ");
}
printf(" ]");
}
You need to allocate memory dynamically to use it.
Use the printf in the code below to define precision.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arraySize = 0;
scanf("%d",&arraySize);
double *vector = (double *) calloc(arraySize, sizeof(double));
for(int i=0; i<arraySize; i++) {
scanf("%lf", &vector[i]);
}
printf("VECTORS:[");
int a;
for(a=0;a<arraySize;a++) {
printf(" %.3lf",vector[a]);
if (a<(arraySize-1)) {
printf(",");
} else {
printf(" ");
}
}
printf("]");
}
Change your for loop to take 3 elements at once.
for(a=0;a<arraySize;a+=3) {
printf("VECTORS:[%lf", vector[a]);
if (a+1 < arraySize) printf(", %lf", vector[a+1]);
if (a+2 < arraySize) printf(", %lf", vector[a+2]);
printf("]\n");
}
I have assignment to write program that sort an array and search for a specific number, that part I've already done, My problem is how to Initialize the array in the size that the user sets with random values smaller than 500? I know how to do that with known size but not with unknown size?
example for input/output:
"Please enter the size of the array:
5"
This will help you.
int main(void)
{
int n,i;
n=rand()%500; // Get random value
int arr[n]; // Initialize the dynamic array
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
// Do your stuff
}
You can do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printArray(int* p, int size)
{
for (int j = 0; j < size; ++ j) printf("%d ", p[j]);
printf("\n");
}
int main(void) {
srand(time(NULL)); // Start with a random seed based on time
int n = 0;
printf("Which array size do you need?\n");
if (scanf("%d", &n) != 1 || n < 1)
{
printf("Wrong input\n");
exit(0);
};
printf("Creating random array of size %d\n", n);
int* p = malloc(n * sizeof(*p)); // Reserve memory
for (int j = 0; j < n; ++j) p[j] = rand() % 500; // Generate random numbers
printArray(p, n); // Print the result
free(p); // free the allocated memory
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.