I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* user;
char* passwd;
int nr;
void test()
{
int i=0;
for(i=0;i<argc;i++)
printf("Hello %s \n",user);
}
int main(int argc,char*argv[])
{
int i;
nr=argc;
for (i=0; i<argc; i++)
{
user=strdup(argv[i]);
}
test();
return 0;
}
The result is the argv[argc] on all the positions. How can I fix this? I wwant to have that test() outside the loop.
**
EDIT
**
After the ANSWERS here this is my new code, which is not working. Can anyone say why?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* user;
void test(int n)
{
int i=0;
for(i=0;i<n;i++)
printf("%s \n",user[i]);
}
int main(int argc,char*argv[])
{
user = (char*) malloc(argc*sizeof(char));
int i;
for (i=0;i<argc;i++)
{
user[i]=argv[i];
}
test(argc);
return 0;
}
You are assigning to both password and user at each iteration of the for loop. The final values you see are from the last iteration. Also, there is memory leak due to overwriting the pointers from previous strdup calls. In fact, you do not need a loop:
int main(int argc,char*argv[])
{
if(argc == 3) {
user=strdup(argv[1]);
passwd=strdup(argv[2]);
} else {
// error: usage
}
test();
return 0;
}
If you want to have multiple user/password combinations:
char *user[256], *passwd[256];
void test(int n) {
int i;
for(i=0;i<n;i++)
printf("Hello %s \n",user[i]);
}
int main(int argc,char*argv[])
{
int i;
for(i = 0; i < argc && i < 256; i+=2) {
user[i]=strdup(argv[i]);
passwd[i]=strdup(argv[i+1]);
}
test(argc);
return 0;
}
Because you overwrite the pointers user and passwd in every iteration. Hence, you'll only see the last string.
If you can tell your aim of the program, a better answer can be provided. Because I am not sure whether you want to read one user and passwd Or an array of users and passwds.
After you edit, I see you want to read an array of strings:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** user;
// or char *user[100]; /* If you want a fix length array of pointers. Now, you dont have to malloc. /*
char* passwd;
int nr;
void test(int argc)
{
int i=0;
for(i=0;i<argc;i++)
printf("Hello %s \n",user[i]);
}
int main(int argc,char*argv[])
{
int i;
nr=argc;
user = malloc(argc*sizeof(char*));
for (i=0; i<argc; i++)
{
user[i]=strdup(argv[i]);
}
test(argc);
return 0;
}
Of course; in test() you don't use i other than a loop variable and in main() you keep overwriting the previous value of user and passwd. In effect, what you do is:
user = strdup(argv[0]); /* Note: argv[0] is the program name. */
passwd = strdup(argv[0]);
user = strdup(argv[1]);
passwd = strdup(argv[1]);
user = strdup(argv[2]);
passwd = strdup(argv[2]);
user = strdup(argv[3]);
passwd = strdup(argv[3]);
printf("%s %s \n", user, passwd);
With this information, can you fix your program?
$ cat trash.c
#include <stdio.h>
#include <string.h>
void test(FILE* stream, char* usr, char* pass) {
fprintf( stream, "%s#%s\n", usr, pass);
}
int main(int argc, char** argv) {
int i = 1;
if (argc % 2) {
while(argv[i]) {
test(stdout, argv[i], argv[i + 1]);
i += 2;
}
}
return 0;
}
$ clang trash.c
$ ./a.out user1 pass1 user2 pass2
user1#pass1
user2#pass2
$
also if you call strdup() don't forget to free memory, because strdup called malloc().
Related
Fairly new to C, I am trying to read a file of multiple words using bash indirection, and put the words into a string array. The end of the file is marked with a -1.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[400000];
init(words);
int i = 0;
do{
printf("%s",words[i]);
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int i = 0;
do{
fgets(words[i],1024,stdin);
i++;
}while(!strcmp(words[i],"-1"));
}
This gives me a segmentation fault, if any other information is needed I'm more than happy to provide it.
If I guessed correctly, '400000' means the max lines the user can input. But the default size of stack on Windows OS is 1M, sizeof(void*) * 400000 = 1,600,000...
The other thing is that you have not allocated memory for every line.
So, I try to correct your code like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE 4000 // '400000' is really too big!
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[MAX_LINE];
memset(words, 0 , sizeof(words));
init(words);
int i = 0;
do{
printf("%s",words[i]);
delete words[i];
words[i] = nullptr;
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int maxLen = 1024;
int i = 0;
do{
words[i] = new char[maxLen];
memset(words[i], 0, maxLen);
fgets(words[i], maxLen, stdin);
i++;
}while(!strcmp(words[i],"-1") && i < MAX_LINE);
}
i wrote some code that is supposed to find the location of a given string in an array of strings.
problem is- it doesn't give the location. it gives something else.
i understand that probably the problem has to do with the differences between the pointers that are involved- a previous version that dealt with finding the position of a letter in a word worked well.
after a lot of attempts to figure out where is the bug, i ask your help.
kindly, explain me what should be done.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int what (char * token);
main()
{
int i=0;
char string[]="jsr";
char *token;
token=&string[0];
i=what(token);
printf(" location of input is %d \n", i);
return 0;
}
int what (char * token)
{
int i=1;
char *typtbl[]={"mov",
"cmp",
"add",
"sub",
"not",
"clr",
"lea",
};
char * ptr;
ptr=(char *)typtbl;
while (!(strcmp(ptr,token)==0))
{
ptr=(char *)(typtbl+i);
i++;
}
return i;
}
As pointed out, you did not design function what properly. What value should it return if your search function go through all the pointers but does not find the desired string? Typically in that case return -1 would be a choice to indicate nothing found. Also in this case, using a for loop would probably be more suitable, you can just return the index immediately instead of going through all pointers.
int what(char *token)
{
char *typtbl[] = {
"mov",
"cmp",
"add",
"sub",
"not",
"clr",
"lea",
};
for( size_t i = 0; i < sizeof(typtbl)/sizeof(char*); ++i )
{
char *ptr = typtbl[i];
if(strcmp(ptr, token) == 0)
{
return i; // found something
}
}
return -1; // found nothing
}
A cleaner working version.
Main issue is in the (char *)(typtbl+i) replaced by typtbl[i] in the following code. typtbl+i is equivalent to &typtbl[i], so if my memory is good, it's a pointer on the pointer of the string and not the pointer of string itself
I added a NULL at the end of the array to be able to stop if the string is not present and return -1 to clearly say it was not found.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int what(char *token);
int main()
{
int i = 0;
char string[] = "jsr";
i = what(string);
printf(" location of input is %d \n", i);
return 0;
}
int what(char *token)
{
char *typtbl[] = {
"mov",
"cmp",
"add",
"jsr",
"not",
"clr",
"lea",
NULL
};
int i = 0;
while(typtbl[i] && !(strcmp(typtbl[i], token) == 0)) {
++i;
}
if(!typtbl[i])
i = -1;
return i;
}
char *token; token=&string[0]; was useless because string == &string[0].
A few things:
Your main function is missing its return type.
The while loop in what doesn't stop when the element isn't found. Therefore you are reading out of bounds.
This should do the work w/o pointer arithmetic.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int what (char * token);
int main(){
int i=0;
char string[]="jsr";
char *token;
token=&string[0];
i=what(token);
printf(" location of input is %d \n", i);
return 0;
}
int what (char * token){
unsigned int i=0;
char *typtbl[]={"mov",
"cmp",
"add",
"sub",
"not",
"clr",
"lea",
};
unsigned int typtbl_x_size = sizeof(typtbl)/sizeof(typtbl[0]);
char * ptr;
ptr=typtbl[i];
while (!(strcmp(ptr,token)==0)){
i += 1;
if (i >= typtbl_x_size){
printf("element not in list\n");
return -1;
}
ptr=typtbl[i];
}
return i;
}
I am creating a struct called Job and I want to create an array of struct Job. The name of my array is jobQueue I populate the array using commandline args. The instructor has it set up to where **args is being used. After the user inputs the name of the job and the execution time it gets added to the array. However, when I try to print jobQueue[0].name using the list() funct I have written, the name does not get printed. I'm trying to get my code set up to where I can print the name. I have provided a minimal version of my overall project that just focuses on the specific problem I am encountering and should compile and run fine.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include <sys/wait.h>
#include <stdint.h>
#define EINVAL 1
#define E2BIG 2
#define MAXMENUARGS 7
//structure job initialize
struct Job {
//initializing name variable
char *name;
int executionTime;
};
//init the array
struct Job jobQueue[5] = {0};
//cmd function provided by intructor
int cmd_run(int nargs, char **args) {
int execT;
sscanf(args[2], "%d", &execT);
run(args[1], execT);
return 0;
}
//cmd function provided by intructor
void cmd_list() {
list();
}
//cmd function provided by intructor
static struct {
const char *name;
int (*func)(int nargs, char **args);
} cmdtable[] = {
/* commands: single command must end with \n */
{ "r", cmd_run},
{ "run", cmd_run},
{ "list\n", cmd_list}
};
//cmd function provided by intructor
//this is the function that handles the arguments entered by the user
//provided it just in case someone needs to see how arguments are being
//processed
int cmd_dispatch(char *cmd) {
time_t beforesecs, aftersecs, secs;
u_int32_t beforensecs, afternsecs, nsecs;
char *args[MAXMENUARGS];
int nargs = 0;
char *word;
char *context;
int i, result;
void *Dispatcher(void *arg);
for (word = strtok_r(cmd, " ", &context);
word != NULL;
word = strtok_r(NULL, " ", &context)) {
if (nargs >= MAXMENUARGS) {
printf("Command line has too many words\n");
return E2BIG;
}
args[nargs++] = word;
}
if (nargs == 0) {
return 0;
}
for (i = 0; cmdtable[i].name; i++) {
if (*cmdtable[i].name && !strcmp(args[0], cmdtable[i].name)) {
assert(cmdtable[i].func != NULL);
/* Call function through the cmd_table */
result = cmdtable[i].func(nargs, args);
return result;
}
}
printf("%s: Command not found\n", args[0]);
return EINVAL;
}
//adds job to the array using user arguments
void run(char name[], int executionTime) {
//creates a job using the arguments specified by user
struct Job job = {name, executionTime};
jobQueue[0] = job;
printf("\nJob added to queue now please type 'list'\n");
}
//name will not print here
void list() {
printf("\nSee how the name will not print below?\n");
char executionTimeStr[5];
for (int c = 0; c < sizeof (jobQueue) / sizeof (jobQueue[0]); c++) {
//prints job info formatted
if (jobQueue[c].name != NULL) {
sprintf(executionTimeStr, "%d", jobQueue[c].executionTime);
//job name will not print here, output is just left blank
printf("%s %20.8s", "Name", "ExecTime");
printf("%-10.15s %11.3s\n",
jobQueue[c].name,
executionTimeStr
);
}
}
}
int main(int argc, char *argv[]) {
printf("Welcome to our batch job scheduler\n");
printf("Please enter the following exactly: 'run job1 10' \n");
//ignore this, it handles my commandline parser
char *buffer;
size_t bufsize = 64;
buffer = (char*) malloc(bufsize * sizeof (char));
if (buffer == NULL) {
perror("Unable to malloc buffer");
exit(1);
}
while (1) {
printf("User Input: ");
getline(&buffer, &bufsize, stdin);
cmd_dispatch(buffer);
}
//ignore this, it handles my commandline parser
return 0;
}
I have the following code but the result is null for all components of the structure:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _TransactionType
{
char field1[20];
char field2[20];
}TransactionType;
int main(int argc, char *argv[]) {
int i;
int numreg = 0;
char temp[12];
TransactionType *dbTransaction;
dbTransaction = (TransactionType*) calloc(10,sizeof(TransactionType));
for(i=0; i<5;i++)
{
memset(temp,0,sizeof(temp));
sprintf(temp,"%d",i);
strcpy(dbTransaction->field1, temp);
dbTransaction->field1[strlen(dbTransaction->field1)] = '\0';
strcpy(dbTransaction->field2, temp);
dbTransaction->field2[strlen(dbTransaction->field2)] = '\0';
numreg++;
dbTransaction++;
}
printf("reg = %d\n", numreg);
for (i=0; i<numreg;i++)
{
printf("dbTransaction->field1 = %s\n",(dbTransaction + i)->field1);
printf("dbTransaction->field2 = %s\n",(dbTransaction + i)->field2);
}
return 0;
}
i need to recover the structure values.
Please any kind of help will be appreciate
Thanks in advance for your help
You should add error checking and casting of calloc values is discouraged, but the reason your code doesn't work is that you advance dbTransaction pointer in your loop, but never rewind it. The prints you're making are actually of elements 5-9 of the array while you fill elements 0-4.
See the corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _TransactionType
{
char field1[20];
char field2[20];
}TransactionType;
int main(int argc, char *argv[]) {
int i;
int numreg = 0;
char temp[12];
TransactionType *dbTransaction;
TransactionType *dbTransactionRoot;
dbTransaction = (TransactionType*) calloc(10,sizeof(TransactionType));
dbTransactionRoot = dbTransaction;
for(i=0; i<5;i++)
{
memset(temp,0,sizeof(temp));
sprintf(temp,"%d",i);
strcpy(dbTransaction->field1, temp);
dbTransaction->field1[strlen(dbTransaction->field1)] = '\0';
strcpy(dbTransaction->field2, temp);
dbTransaction->field2[strlen(dbTransaction->field2)] = '\0';
numreg++;
dbTransaction++;
}
printf("reg = %d\n", numreg);
for (i=0; i<numreg;i++)
{
printf("dbTransaction->field1 = %s\n",(dbTransactionRoot + i)->field1);
printf("dbTransaction->field2 = %s\n",(dbTransactionRoot + i)->field2);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int countArrayChars(char *strArray[]){
int i=0;
while (strArray[i] != '\0'){
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[]) {
char *dog[] = {"dog"};
countArrayChars(dog);
For some reason, it prints "5".
Shouldn't it print 3?
I even tried to put \0 after the "g".
You declare array of string and initialize it with dog.
char *dog[] = {"dog"};
Actually it represented as
dog[0] = "Dog"; //In your case only element index with 0.
...............
...............
dog[n] = "tiger"; //If there Have n+1 element
Hence your array size is 1. Which hold constant string dog. To access it you should use dog[0].
So without less modification you can use your code as:
int countArrayChars(char *strArray[])
{
int i=0;
while (strArray[0][i] != '\0')
{
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[])
{
char *dog[] = {"dog"};
countArrayChars(dog);
}
Or if you want to declare a string use
char *dog = "dog";
or
char dog[] = "dog";
Please try this
#include <stdio.h>
#include <stdlib.h>
int countArrayChars(char *strArray){
int i=0;
while (strArray[i] != '\0'){
i++;
}
printf("%d\n", i);
return i;
}
int main(int argc, const char * argv[]) {
char *dog[] = "dog";
countArrayChars(dog);
}