Getting array declaration error - c

I have this array called arr_[6], having an idea of including six strings...but when I declare this array compiler throws error.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char arr_1[]= {"My_name","your Name", "His Name"};
char *arr_p;
arr_p = malloc(sizeof(char)*6);
arr_p = arr_1;
printf("%s\n",*arr_p);
system("PAUSE");
return 0;
}
Shown errors are as follows:
> main.c: In function `main': main.c:9: error: excess elements in char
> array initializer main.c:9: error: (near initialization for `arr_1')
> main.c:9: error: excess elements in char array initializer main.c:9:
> error: (near initialization for `arr_1')
>
> make.exe: *** [main.o] Error 1
Please help me!

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
const char *arr_1[]= {"My_name","your Name", "His Name"}; // has to be an array of <char *>
//arr_p is not necessary
printf("%s\n",*arr_1); // will print the first string, "My_name"
printf("%s\n",arr_1[1]); // will print the second string, "your Name"
printf("%s\n",arr_1[2]); // will print the third string, "His Name"
system("PAUSE");
return 0;
}

I believe what you're looking for is this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char* arr_1[]= {"My_name","your Name", "His Name", NULL};
char** arr_p;
arr_p = arr_1;
i = 0;
while (arr_p[i] != NULL)
{
printf("%s\n",(arr_p[i]));
++i;
}
system("PAUSE");
return 0;
}
These are the list of changes I've made:
Use char* arr_1[] to declare an array of strings, since each string is an array of characters.
If you need a pointer to a char*, you need to declare the pointer to be of datatype char**
Used NULL as the last element in the array, so that you know when you've reached the end of the array of strings.
Use a while loop to iterate over all the strings.

Related

C invalid initializer on empty line and invalid arguement on a while loop

I am getting those following errors in this code I am not sure what causes them. Since one of them happens on an empty line where nothing happens. The other is on a while loop that doesn't take an argument I believe.
Error message:
test.c: In function ‘main’:
test.c:28:15: warning: assignment to ‘char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
28 | checker = decrypt(Ciphertext,key,iv);
| ^
test.c:31:8: warning: format not a string literal and no format arguments [-Wformat-security]
31 | printf(key);
| ^~~~~~
/usr/bin/ld: /tmp/ccGWk1m2.o: in function `main':
test.c:(.text+0x57): undefined reference to `readWord'
/usr/bin/ld: test.c:(.text+0x8c): undefined reference to `decrypt'
collect2: error: ld returned 1 exit status
#include <stdio.h>
#include <stdlib.h>
#include <conf.h>
#include <evp.h>
#include <err.h>
#include <string.h>
#include <ctype.h>
unsigned char *readword(FILE *fp);
int decrypt(unsigned char *Ciphertext, unsigned char *key,unsigned char *iv);
int main (void)
{
char *key = NULL;
char *iv = "aabbccddeeff00998877665544332211";
char *Plaintext = "This is a top secret.";
char *Ciphertext = "764aa26b55a4da654df6b19e4bce00f4ed05e09346fb0e762583cb7da2ac93a2";
char *checker;
// invalid initializer on this line for some reason
FILE words;
words = (fopen("words", "r"));
while(1) { // invalid argument when I am not even using one? it's C standard loop right?
key = readword(words);
if (!key){
printf("the key was not found");
break;
}
else{
checker = decrypt(Ciphertext,key,iv);
if(strcmp(checker,Plaintext)){
printf("the correct key is ");
printf(key);
}
free(key);
free(checker);
}
}
return 0;
}

process returned -1073741819 <0xC0000005>

i am a beginner to coding and learning c language as my first step.
when i use string function the program returns with a value without showing output. using minGW as compiler
i tried to add string.h header folder
string
from below follows code
''''
#include <stdio.h>
#include <conio.h>
int main()
{
/*
int strlen(string);
*/
char name = { 's','i','l','a','m','\0' };
int length;
length = strlen(name);
printf("the length of %s is %d\n", name, length);
getch();
return 0;
}
'''
code ends here
expected to to print length of the char name but it crashes
as in build log
"Process terminated with status -1073741819 "
in build messages
warning: passing argument 1 of 'strlen' makes pointer from integer without a cast [-Wint-conversion]|
note: expected 'const char *' but argument is of type 'char'|
thanking you for looking into
You declare name as a char yet you treat it like an array. To declare name as a char array, use:
char name[] = { 's','i','l','a','m','\0' };
Also since you reference the function strlen(), you must add the header file:
#include <string.h>
Enjoy:
#include <stdio.h>
#include <string.h>
int main()
{
// single char can't store that string
// so we have to declare an array of chars
char name[] = {'s', 'i', 'l', 'a', 'm', '\0'};
// also we can use string literal syntax:
// char name[] = "silam";
int length = strlen(name);
printf("the length of %s is %d\n", name, length);
getc(stdin);
// i don't have <conio.h> so i call 'getc' instead of 'getch'
return 0;
}

C - issue with reading in from command line - assignment makes pointer from integer without a cast

Having an issue with reading in from the command line into an array of integers.
Intent is to parse the entered line by spaces/tabs and then atoi() each individual number into the appropriate array slot.
Relevant code:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main()
{
int nums[100];
int count = 0;
readInput(&nums, &count);
return 0;
}
functions.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
void readInput(int *nums[], int *count);
#endif // FUNCTIONS_H_INCLUDED
functions.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
#define delims " \t\r\n"
#define MAX_LEN 128
void readInput(int *nums[], int *count)
{
char *input = malloc(MAX_LEN);
char *buffer;
gets(input);
buffer = strtok(input, delims);
nums[(*count)++] = atoi(buffer);
while ((buffer = strtok(NULL, delims)) != NULL)
nums[(*count)++] = atoi(buffer);
buffer = strtok(NULL, delims);
}
The lines in functions.c with nums[(*count)++] = atoi(buffer); are flagging with the warning "warning: assignment makes pointer from integer without a cast".
And from main.c, the line readInput(&nums, &count); is flagging with "warning: passing argument 1 of 'readInput' from incompatible pointer type".
The odd thing is this program works when run and any attempts to add in casting or dereferencing has resulted in the warnings being subdued, but the program crashing when run.
When you declare your function:
void readInput(int *nums[], int *count);
the argument declaration int *nums[] is an array of pointers, not a pointer to an array which is what you call it like with &nums.
However, you don't need to pass a pointer to the array here. Arrays naturally decays to pointers to their first element. And when you declare an array as an argument to a function (like the declaration of nums in the function prototype above) it's really a pointer.
When you declare function arguments, a declaration like int nums[] is the same as int *nums.
So the declaration of readInput should really be
void readInput(int *nums, int *count);
If you do that change (including the function definition of course), and call it like
readInput(nums, &count);
then everything should work out fine.

Finding a unique character

My task is to compare some words and to find a character which is not used in both of them. Here is my code. But I'm getting a warning:
[Warning] passing argument 1 of 'ret' makes pointer from integer without a cast [enabled by default].
And when I'm trying to run it it says consolepauser.exe stopped working
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char ret(char a[1][10],char b[3][10])
{
int i,j,p,t;
for (i=0;i<1;i++)
for (j=0;j<10;j++)
for (p=0;p<3;p++)
for (t=0;t<10;t++)
{
if (tolower(a[i][j]==tolower(b[p][t])))
{
p=3;
break;
}
if (p==2)
if (t==9) return tolower(a[i][j]) ;
}
return 'N';
}
int main(int argc, char *argv[]) {
char k[3][10]={"cHaOs","TOP","blAa"};
char b[1][10]={"SomeThIng"};
char q[1][10]={"HaPa"};
if (ret(b[1][10],k[3][10])='N') printf("No character") ;
else printf("%c",ret(b[1][10],k[3][10])) ;
return 0;
}
You should pass the parameters as:
if (ret(b, k) == 'N') printf("No character");
else printf("%c", ret(b, k));
[Warning] passing argument 1 of 'ret' makes pointer from integer without a cast
b[1][10] is a char, not a variable of type char [1][10], you should call ret() like this: ret(b, k). Others are similar.
Note: the valid indexes of char b[1][10]; are b[0][0], b[0][1], ..., b[0][9], the indexes in `b[1][10]1 are out-of-bounds, and will cause undefined behavior.
Here is a syntax fixed version of your code, you may want to compare it with your original code to find out other problems in it:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char ret(char a[1][10],char b[3][10])
{
int i,j,p,t,e,r;
for (i=0;i<1;i++)
for (j=0;j<10;j++)
for (p=0;p<3;p++)
for (t=0;t<10;t++)
{
if (tolower(a[i][j])==tolower(b[p][t]))
{
p=3;
break;
}
if (p==2)
if (t==9) return tolower(a[i][j]) ;
}
return 'N';
}
int main(int argc, char *argv[]) {
int i,j,p,t,e,r;
char a,h;
char k[3][10]={"cHaOs","TOP","blAa"};
char b[1][10]={"SomeThIng"};
char q[1][10]={"HaPa"};
if (ret(b,k)=='N') printf("No character");
else printf("%c",ret(b,k));
return 0;
}

Segmentation fault while processing argv

This procedure should convert a string that contains a set of double numbers separated by comma (e.g. 7.2,9.5,-5.515) to a vector of double type.
void ToDoubleVec(int d,const char* commaSeparated,double *result)
{
int i;
result[0]=atof(strtok(commaSeparated,","));
for(i=1;i<d;i++)
result[i]=atof(strtok(NULL,","));
}
Here is the snippet of program that calls it:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc,char** argv)
{
...
int i,dim=atoi(argv[1]);
double *lower;
lower = malloc(dim*sizeof(double));
ToDoubleVec(dim,argv[2],lower);
...
}
Debugger's output:
40 lower = malloc(dim*sizeof(double));
(gdb) s
42 ToDoubleVec(dim,argv[2],lower);
(gdb) s
ToDoubleVec (d=2, commaSeparated=0x7fffffffe9d3 "2.3,-62.1", result=0x603010) at testPSO.c:11
11 result[0]=atof(strtok(commaSeparated,","));
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff77f56bb in ?? () from /lib/x86_64-linux-gnu/libc.so.6
Why doesn't it work? I was sure that I've allocated enough memory for the array and also parameters seems to be passed correctly.
You can reduce your code to this SSCCE (Short, Self-Contained, Correct Example), which crashes nicely when you leave out #include <string.h> and does not compile cleanly when you add #include <string.h>:
segv.c: In function ‘ToDoubleVec’:
segv.c:8:5: warning: implicit declaration of function ‘strtok’ [-Wimplicit-function-declaration]
segv.c:8:20: warning: initialization makes pointer from integer without a cast [enabled by default]
segv.c:14:20: warning: assignment makes pointer from integer without a cast [enabled by default]
Code:
#include <stdlib.h>
//#include <string.h>
static void ToDoubleVec(int d, const char* commaSeparated, double *result)
{
int i;
result[0] = atof(strtok(commaSeparated, ","));
for (i = 1; i < d; i++)
result[i] = atof(strtok(NULL, ","));
}
int main(void)
{
int dim = 2;
double *lower = malloc(dim*sizeof(double));
char arg[] = "7.2,9.5,-5.515";
ToDoubleVec(dim, arg, lower);
}
Passing the return value from a function such as strtok() which can return a null pointer directly to a function such as atof() which does not tolerate null pointers is foolhardy; it leads to crashes. If everything is correct, you'll be OK; if not, you'll crash and burn.
The unchecked memory allocation is a similar problem; you didn't even check that dim was non-zero (and non-negative) before doing the memory allocation in the original.
#include <assert.h>
#include <string.h>
#include <stdlib.h>
static void ToDoubleVec(int d, char *commaSeparated, double *result)
{
int i;
char *number = strtok(commaSeparated, ",");
if (number != 0)
{
result[0] = atof(number);
for (i = 1; i < d; i++)
{
number = strtok(NULL, ",");
if (number != 0)
result[i] = atof(number);
}
}
}
int main(void)
{
int dim = 2;
double *lower = malloc(dim*sizeof(double));
char arg[] = "7.2,9.5,-5.515";
assert(lower != 0);
ToDoubleVec(dim, arg, lower);
}
You could — and in one version of the code I did — add error printing to report if the tests on number failed. But the crash is caused by the implicit declaration of strtok() as returning int and not char *.
I have tried to compile your code, and the compiler warned me that strtok() takes as input a char* and not a const char*. Then I have tried this code, and it is working correctly:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void ToDoubleVec(int d, char* commaSeparated,double *result);
int main(int argc,char** argv)
{
int i,dim=atoi(argv[1]);
double *lower;
lower = malloc(dim*sizeof(double));
ToDoubleVec(dim,argv[2],lower);
for (i=0; i<dim; ++i) {
printf("%f\n", lower[i]);
}
return 0;
}
void ToDoubleVec(int d, char* commaSeparated,double *result)
{
int i;
result[0]=atof(strtok(commaSeparated,","));
for(i=1;i<d;i++)
result[i]=atof(strtok(NULL,","));
}
So try to change const char* to char*, and check the input you pass to your program, maybe it is not correct and this could be the problem.

Resources