diffculty in entering strings in C using pointer - c

The following program works in gcc but on giving the value of T = 6, this program continues and does not end on asking for input strings. Any help guys if you recognise whats wrong with this program?
int main()
{ int T,i,j;
char *strings[T];
printf("Enter the Number of Strings to Reverse : \n");
scanf("%d ",&T);
for(i=0;i<T;i++)
{ strings[i] = (char *)malloc(100*sizeof(char));
scanf("%s\n",strings[i]);
}
for(i=0;i<T;i++)
{printf(" The String %d is : %s\n",i+1,strings[i]);
}
return 0;
}

T is not initialised (Remember in C++, local scope variables are not automatically initialised) :
int T= 6;

T is not initialized inside main() therefore has an undefined value.
char *strings[T] creates an array of char * pointers of an undefined length.
Fix this using:
int T=6;
Or, given T is in fact constant:
const int T=6
or perhaps better
#define T 6
Feel free to use a more mnemonic name than T.

Related

Newline Constants in C

My code:
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
In the above code the output:
value of area: 50
Process returned 0 (0x0) execution time : 2.909 s
Press any key to continue.
There is a new line inserted, but when I change NEWLINE="\n" despite knowing it is a char type, there is no error prompted by the compiler and no newline printed out. Why???
Also, I modified my code as,
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
const char k="hjk";
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
printf("%c", k);
return 0;
}
The output is only the area calculated and the new line but k is not printed out. I also find this very weird! Can you please give suggestions?
Please be kind enough with the suggestions and point out my mistakes because I am a beginner at C.
The problem is that you are trying to save a string as a char, so you have to change const char k = "hjk" to const char k[]="hjk" and print it using %s instead of %c.
#include<stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
const char k[]="hjk";
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
printf("%s", k);
return 0;
}
Some clarification: if you save a "string" without specifying that it is an array of characters char[], if you try to print it as a char %c a warning would be generater (warning: incompatible pointer to integer conversion initializing 'const char' with an expression of type 'char [4]') and if you try to print it as a array of characters %s (string) you are going to receive a segmentation fault.
when I change NEWLINE="\n" despite knowing it is a char type, there is no error prompted by the compiler
const char NEWLINE = "\n"; is invalid C. The reason why it is invalid is explained in detail here: "Pointer from integer/integer from pointer without a cast" issues
The compiler is not required to produce an "error", but it is required to produce some sort of diagnostic message. See What must a C compiler do when it finds an error?
Why your compiler decided to spew out a binary regardless of getting fed invalid C is anyone's guess. You have to ask the people who made the compiler. In case of gcc, you won't find an answer, because this is completely undocumented behavior.
And therefore, any output you get from such a "non C" program is also completely non-deterministic, unless a compiler documented the behavior among non-standard compiler extensions. gcc did not.
Similarly, const char k="hjk"; is also invalid C.
k seems an array of char.
Try to use:
const char k[] = "something";
printf("%s", k);
The statement const char k="hjk"; is not valid C code. Apparently, your compiler accepts it and assigns the memory address where the literal string "hjk" begins to k. Both a memory address and a char are implemented as integer numbers, so the memory address is interpreted as the numeric code for a character.
Because k is now, most likely, an unprintable character, printf("%c", k); will print nothing.
Exactly the same happens when you do const char NEWLINE ='\n';.

(windows) DevC++ GCC compiler hangs up or prints infinite characters

I am trying to write some C code, and while running the following, my compiler terminates abruptly, after printing 'A'. Why?
//report expected thing
void Expected(char *s){
int i=0;
int n = sizeof(s)/sizeof(s[0]);
while (i< n)
printf ("%c", s[i]);
printf(" expected.\n");
}
int main(int argc, char *argv){
printf("%c",65); //after this compiler hangs and asks for exit abnormally
char *Arr ={'a'};
Expected(Arr);
return 0;
}
Also, if I put
char *Arr ={"a"}; //note the double quotes
then it starts printing out infinite number of 'a's. Why should this happen?
int n = sizeof(s)/sizeof(s[0]);
is not how to get the length of the array of which the pointer passed as the argument points at the first element.
Pass the size of the array if you want to let your function know that.
char *Arr ={'a'};
Is not good because 'a' is a integer and you converted it to a pointer, then the result has too little chance to be a valid pointer.
char *Arr ={"a"};
is OK because it is a valid pointer, but it will be infinite loop because i is not updated in the while loop.
The type of main() function is implementation-defined. You should use standard type unless you have some reason to use special main().
Your code should be like this:
#include <stdio.h>
//report expected thing
void Expected(const char *s, size_t n){ /* add const because the contents of array won't be modified */
size_t i=0; /* use size_t to match type of n */
while (i < n)
printf ("%c", s[i++]); /* update i */
printf(" expected.\n");
}
int main(void){ /* use standard main(). int main(int argc, char **argv) is the another standard type */
printf("%c",65); //after this compiler hangs and asks for exit abnormally
char Arr[] ={'a'}; /* declare an array instead of a pointer */
Expected(Arr, sizeof(Arr)/sizeof(Arr[0]));
return 0;
}
Finally, if it is really not your produced executable but your compiler that is crashing, throw the broken compiler away and get a new one.

Pointers in C for a rookie

I am just starting to learn programming for a unit I am doing in my engineering course and I have come across pointers. I just wanted some reassurance that I actually understand the concept correctly in terms of using a pointer as an argument in a function. If I understand it correctly, you pass a pointer to an address of a variable you would like to be altered by a separate function called, even though it is a local variable within the scope of the calling function. Does that make sense? I have an example from my text book which I re-wrote. The only thing is they gave it in two incomplete parts and I put it together, filled in the blanks and added the final printf statement in the main function. I'll paste it here:
#include <stdio.h>
#include <stdlib.h>
#define READ_OK 0
#define READ_ERROR 1
int read_num(int lo, int hi, int *num);
int main(int argc, char *argv[])
{
int lo = 0, hi = 0, *num, val;
printf("Please enter a lower bound and an upper bound for your range,respectively\nLower: ");
scanf("%d", &lo);
printf("Upper: ");
scanf("%d", &hi);
num = &val;
if(read_num(lo,hi, &val) != READ_OK)
{
printf("Read error, program abort\n");
exit(EXIT_FAILURE);
}
else
{
printf("You entered %d, press any key to continue: \n", val);
getchar();
}
return 0;
}
int read_num(int lo, int hi, int *num)
{
int next;
printf("Enter a number between %d and %d: ", lo, hi);
while(scanf("%d", &next)==1)
{
if (lo<=next && next<=hi)
{
*num = next;
return READ_OK;
}
printf("%d is not between %d and %d\nTry again: ", next, lo, hi);
}
return READ_ERROR;
}
So is my understanding correct? "val" gets modified in read_num() by passing it's address in the form of pointer "*num", in which the the value for "next" is then written?
PS: is this syntax correct?
PPS: What would this process specifically be called?
Thanks a bunch for any help :)
The *num is not necessary inside the main() function. As you are passing the address of the val inside the read_num() , so any changes from the read_num() will also affect the value inside main() as you are working with the address.
In your program you have basically use two different pointers- one is inside main which is num, and another inside read_num() which is also num, for more understanding see the scope of a variable in c. As the val is inside main so you don't need to use pointer here, because you have the access of changing the value from the main as it is local to it. You will need pointer when you will be changing the value of val outside from the main, or from outside of the scope of the variable.

Why this program stops unexpectedly in the middle of the input

i have written this code for a question on codechef (A4)....when i give the input:
2
4 2
This program stops unexpectedly without taking further input ....can some please point out the mistake in the code?
#include <stdio.h>
#include<math.h>
void number(long int a,int b)
{
int c;
c=b;
int first[c],last[c],e=1,i;
long int d;
d=pow(a,a);
for(i=(c-1);i>=0;i--)
{
last[i]=fmod(d,pow(10,e));
e++;
}
e=1;
while(d>pow(10,(b-1)))
d/=10;
for(i=(c-1);i>=0;i--)
{
first[i]=fmod(d,pow(10,e));
e++;
}
for(i=0;i<c;i++)
printf("%d",first[i]);
printf(" ");
for(i=0;i<c;i++)
printf("%d",last[i]);
printf("\n");
}
int main()
{ int T;
scanf("%d",&T);
while(T--)
{ long int a;
int b;
scanf("%ld %d",a,b);
number(a,b);
}
return 0;
}
scanf("%ld %d",&a,&b);
Using uninitialized variables lead to UB. You should use &a and &b to scan variables
In your code you have
scanf("&ld %d",a,b);
It means you're trying to input integers to the memory locations of values of a and b. For and example let value of a = 1234566466 (long int), and b = 1234 (int). Accordingly 1234 is a memory location which is at the start of the RAM. Tn that area System files are loaded. So you are going to change system behaviour. That is not allowed.
Further when the complier allocate some memory space to your program, you can access only the memory which is inside your memory segment directly. But above statement trying to access another segment.
That's why you get segmentatin fault.
You are passing an integer to a function that expects a pointer, for scanf the "%d" and "%ld" specifiers expect int * and long int * respectively, and you pass int and long int, so when trying to access the integers as if they were memory addresses the segmentation fault occurs.
The correct way to call scanf would be as Gopi said
scanf("%ld %d", &a, &b);
there you pass a and b addresses instead of their values.

Allocating memory for array in struct (in C)

I need to define a type-struct in C that contains an array to be malloc'd as:
#include <stdio.h>
#include <stdlib.h>
typedef struct mine
{
int N;
double *A;
} mine;
int main(int argc, char** argv)
{
int i;
mine *m=malloc(sizeof(mine));
printf("sizeof(mine)=%d\n",sizeof(mine));
scanf("Enter array size: %d",&(m->N));
m->A=malloc((m->N)*sizeof(double));
for(i=0; i < m->N; i++)
m->A[i]=i+0.23;
printf("First array element: %lf",m->A[0]);
return (EXIT_SUCCESS);
}
The program compiles and runs, and the integer assignment seems to work fine. The array is not working as it should, however.
Any suggestions? I would like m to remain a pointer (to pass to functions etc.).
Thanks.
This is your problem:
scanf("Enter array size: %d",&(m->N));
It should be two separate steps:
printf("Enter array size: ");
scanf("%d",&(m->N));
(and for debugging checking:)
printf("The size entered appears to be %d\n", m->N);
That way, you know if you got the value you intended to get!
If #abelenky answered your question fine, but I was always told to cast the results of malloc from the void * it returns into whatever you are actually working with.
mine *m = (mine *)malloc(sizeof(mine));

Resources