when i try to run this code i get the error: error: 'list1' undeclared (first use in this function). But i have declared the variable in main(), I also tried declaring it at the top, under text1,text2 and count. But then it said "initialzer element not constant". I've tried googling it but with no luck. btw the code isn't finished yet but i cant get past this error and just want to fix it. Thank you
#include <stdio.h>
#include <stdlib.h>
char *text1 = "This is a string.";
char *text2 = "Yet another thing.";
int *count = 0;
void printlist(const int* lst){
printf("ASCII codes and corresponding characters.\n");
while(*lst != 0){
printf("0xX '%c' ", *lst, (char)*lst);
lst ;
}
printf("\n");
}
void endian_proof(const char* c){
printf("\nEndian experiment: 0xx,0xx,0xx,0xx\n",
(int)*c,(int)*(c 1), (int)*(c 2), (int)*(c 3));
}
void copycodes(char *text, int *list, int *counter){
while(*text != 0){
*list = *text;
list ;
text ;
}
}
void work(){
copycodes(&text1, &list1, &count);
}
int main(void){
int *list1 = (int *)(malloc(80));
int *list2 = (int *)(malloc(80));
work();
printf("\nlist1: ");
printlist(list1);
printf("\nlist2: ");
printlist(list2);
printf("\nCount = %d\n", count);
endian_proof((char*) &count);
}
CodePudding user response:
As @EugeneSh. said, the variables list1
and list2
are local to main()
, and thus aren't in scope for the other functions. While you could make the globals by simply initializing them to NULL
and then setting them in main()
, it would make more sense to pass list1
as an argument to work()
:
void work(int* list){
copycodes(text1, list, count);
}
A few things to take note of:
You do not need or want to cast the return value from
malloc()
(orcalloc()
for that matter). This is an exception to the usual rule regarding casting pointers.As @melonduofromage said, you would need to use the
sizeof(int)
to tellmalloc()
how large the elements being allocated are. Conversely, you could usecalloc()
instead, which is specifically meant to allocate arrays.list1 = calloc(20, sizeof(int));
When passing a pointer to a function which accepts a pointer argument, you do not want or need to use the reference (
&
) operator for the pointer in question. That would only be needed if you were passing a pointer to a pointer argument.As a general rule, it is better to avoid globals unless the alternative is more confusing. In this case, you would need to pass more arguments to various functions, but the improved decomposition would make it worth it IMAO.
Also as a general rule, if you find yourself using the pattern
var1
,var2
,var3
...varN
, then you should should either bundle the variables into an array if they are related to each other, or else find more descriptive names if they are not.