简体   繁体   English

尝试设置和打印指针的值

[英]Trying to set and print value of pointer

I have some code that prompts a user to read in a file that has the format: [name] [someInt], but not all lines have [name]. 我有一些代码提示用户读取以下格式的文件:[name] [someInt],但并非所有行都具有[name]。 I thus parse each line into a string array, and if it's length of 2, then it has a name and does a strcmp to find a match and then prints out the int associated. 因此,我将每一行解析为一个字符串数组,如果长度为2,则它具有名称,并执行strcmp查找匹配项,然后打印出关联的int。 However, I'm running into some issues where I get 但是,我遇到了一些问题

error: invalid operands to binary * (have 'char *' and 'char *') 错误:对二进制*无效的操作数(具有'char *'和'char *')

when compiling at the printf("%s\\n" *ans); printf("%s\\n" *ans);编译时printf("%s\\n" *ans); line 线

    char * ans = NULL;

//open and read file line by line, below code is in line by line while loop
             char ** res  = NULL;
             char *  p    = strtok (line, " ");
             int n_spaces = 0, i;
             while (p) {
                 res = realloc (res, sizeof (char*) * ++n_spaces);

                 if (res == NULL) {
                     exit (-1); /* memory allocation failed */
                 }

                res[n_spaces-1] = p;
                p = strtok (NULL, " ");
                printf("%d\n", n_spaces);
                if(n_spaces == 2 && (strcmp(name,res[0]) == 0)) {
                    nameMatch = true;
                    printf("MATCH FOUND!\n");
                    ans = res[1];
                    printf("%s\n" *ans);
                    break;
                }
            }
printf("%s\n" *ans);
             ^

You're missing a comma between these arguments. 您在这些参数之间缺少逗号。 The compiler is interpreting the * as multiplication, and not understanding how you expect it to multiply two strings. 编译器将*解释为乘法,而不理解您期望它如何将两个字符串相乘。

Even with this change, you'll (probably?) still get a warning about types. 即使进行了此更改,您(可能吗?)仍然会收到有关类型的警告。 Remove the * entirely; 完全删除* I'm pretty sure you want to pass the string pointer to printf , not the first character of the string. 我很确定您要将字符串指针传递给printf ,而不是字符串的第一个字符。

you are telling that res is NULL. 您说的是res为NULL。 Then, before malloc you are using realloc? 然后,在malloc之前,您正在使用realloc? Your mistake might be this. 您的错误可能是这样。

printf("%s\\n", *ans); instead of printf("%s\\n" *ans); 而不是printf("%s\\n" *ans);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM